Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connection error with Django and PostgreSQL in Ubuntu Server
I have a virtual machine running ubuntu server and I want to set a connection using Django in my pc and a postgre's database in ubuntu server. This is mi first time developing a database in server and I don't know if this is the correct way. I get this: connection = Database.connect(**conn_params) File "C:\Users\RSSpe\Desktop\ProyectoFinalDjango\entorno_virtual\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "192.168.1.3", port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? I have this in my postgresql.conf file: Connection Settings listen_addresses = "*" # what IP address(es) to listen on; # comma-separated list of addresses; # defaults to 'localhost'; use '*' for all # (change requires restart) port = 5432 # (change requires restart) max_connections = 100 # (change requires restart) This is my pg_hba.conf file: # Database administrative login by Unix domain socket local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all all md5 host all postgres all md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication … -
DJANGO JSON filtering nested value
I am trying to figure out how to filter out JSON in DJANGO when the structure looks like this: some random ID is like random generate id like pad1g12312-421df-2131 "data": { "steps":{ "some random ID":{ "name":"name1" } }, "process":{ "some random ID":{ "name":"PROCESS #1", } } I am trying to figure out how to get the name under execution and operation I tried follow with this post: Django JSONField filtering_ object.filter(data__steps__0__name='name1') object.filter(data__process__0__name='PROCESS #1') but it isn't working. I am assuming it's because the Random ID part doesn't work with the 0. Is there a way to do this? Also, I would like to combine the two in the same filtering, like object.filter(data__steps__0__name='name1' or data__process__0__name='PROCESS #1') Is it possible to do that? Thank you -
Add a FileField path to django
I have a map in my app and im trying to 'paint' some territories with kml files. I can get the outlined version if i hardcode the absolute path but since i have multiple kmls im trying to do it with a for loop with a field.kml.path (kml being the Filefield in my model) as per django instructions but it doesnt work . Any idea how to fix that ? view : def map(request): field_list = models.Field.objects.all() context = { "title": "Map", "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) My original map.html var polygon = omnivore.kml("{% static '../media/kml/Arnissa_cherry.kml' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); New version that doesnt work: {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name var polygon = omnivore.kml("{% static '{{field.kml.path}}' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); {% endfor %} -
Microservices framework for Django?
There are quite a few these frameworks for enterprise level players like Java (and Golang) It's a well known knowledge that many people use Django to implement each service within microservices architecture, but I am looking for something that sits on top of this, a framework of frameworks. Like cookiecutter type. Exposing data We all know to commonly expose a model over rest API is to use DRF, but setting it up is a chore, eg. manually creating ModelViewSet and setting up routers. In an non-public facing environment that assuming no auth needed, for the most basic setup, I just want to use decorator on the model, and it will do all the manual work behind the scene, eg. dynamically creating the viewset and register to urls, similar concept to viewflow's rest framework support. # in accounts app @soa_data_provider(...) class User(models.Model) .... which will default exposes the data in /api/accounts/models/user/ Consuming data Could potentially utilise django-rest-models like @soa_data_consumer(...) class User(models.Model): field = models.IntegerField() ... class Meta: # basic django meta Stuff verbose_name = 'Users' class APIMeta: pass Syncing data Referring to the @soa_data_provider decorator mentioned above, maybe using tools like rabbitmq to publish changes automatically over some convention naming/routes/etc etc, … -
Cannot alter tables after Django migration in posgres DB
I really need to know why in the world we cannot change the column types after we do the migrations to Postgres DB. I already created my models by python manage.py makemigrations then do migrate. Everything looks fine and tables are created on the postgres DB. class test_API(models.Model): IDnumber = models.IntegerField(unique = True, primary_key = True, null=False, editable = False, blank=True) State = models.CharField(max_length = 256, null = True) Exlcludmethod = models.CharField(max_length=256, null=True) class test_API_2(models.Model): Idnumber = models.Foreignkey(test_API, max_length = 256, blank=False, null = False) value = models.CharField(max_length=128, default="") last_updated = models.DateTimeField(auto_now=True) Lets say we want to make change to IDnumber column from Integerfield to Charfield. class test_API(models.Model): IDnumber = models.CharField(null=False, blank=False) State = models.CharField(max_length = 256, null = True) Exlcludmethod = models.CharField(max_length=256, null=True) and run the python manage.py makemigrations again return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "test_API" already exists How can we modify/change column types and do migrations. What is the proper way of doing this ? Using Django:Django==4.0.3 Python = 3.9.1 Posgresql = 2.9.3 Django migrations using RunPython to commit changes django 1.7 migrate gets error "table already exists" -
Duplicating a model while searching
I wrote simple query schare used ListView class: class HomeView(ListView): model = Person template_name = "phones/home_page.html" context_object_name = 'people' def get_queryset(self): query = self.request.GET.get('q') if query: object_list = self.model.objects.filter(Q(name__icontains=query) | Q(surname__icontains=query) | Q(phone__phone__icontains=query) | Q(mail__mail__icontains=query)) else: object_list = self.model.objects.all() return object_list I used 3 models one of them: class Phone(models.Model): person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE, related_name='phone') phone = models.CharField(max_length=50, blank=True) One of 'Q' is in ForeignKey. The problem is when I enter '1' for example, it duplicates the model. example I know why is happen but can I reduce the same model to 1 -
Twitter is not showing thumbnail for my page
I am trying to add a thumbnail when a user shares a page of my site. According to the documentation, it is necessary to define some parameters for the card i.e. image, title, description, etc. I am using the snippet on the page, however, when I share the card, my image does not show up. This is my current <head> <!-- Twitter open-graph tags --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:creator" content="@twitter_user"> <meta name="twitter:site" content="@twitter_user"> <meta name="twitter:image:alt" content="Site name"> <meta name="twitter:image" content="https://examplesite.com/static/landing/img/img.png" /> <meta name="twitter:title" content="{% trans 'Site Title' %} - Site" /> <meta name="twitter:description" content="{% trans 'Site description' %}" /> <meta name="twitter:url" content="https://www.examplesite.com{% url path %}"> I am using the absolute path, i.e.: https://examplesite.com/img/img.png (adding my domain to load the image), also using the HTTPS protocol, with an image in PNG format of 80kb and 1200x630px. When I want to validate my site with this tool, I get this result, in which the image is not visible and also, according to the log, not all the defined parameters are detected. -
Add a kml file into django
I have a map in my app and im trying to 'paint' some territories with kml files. I can get the outlined version if i hardcode the absolute path but since i have multiple kmls im trying to do it with a for loop with a field.kml.path (kml being the Filefield in my model) as per django instructions but it doesnt work . Any idea how to fix that ? view : def map(request): field_list = models.Field.objects.all() context = { "title": "Map", "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) My original map.html var polygon = omnivore.kml("{% static '../media/kml/Arnissa_cherry.kml' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); New version that doesnt work: {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name var polygon = omnivore.kml("{% static '{{field.kml.path}}' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); {% endfor %} -
Nginx 502 Bad Gateway error on EC2 Instance with dango
I'm using Nginx in my EC2 instance to attach my domain from route 53 with my Django app which is running in a docker container, it was working totally fine but as I move my database to the RDS and after moving it my application is not working there, Nginx is throwing me the error attached below: 2022/04/07 21:15:40 [error] 9#9: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 202.47.34.198, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://172.20.0.3:9000", host: "sub.domain.com", referrer: "http://sub.domain.com/" /etc/nginx/sites-available/default server { root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name sub.domain.com; location / { proxy_pass http://localhost:80; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 100M; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/sub.domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/sub.domain.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 } server { if ($host = sub.domain.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 8080 default_server; listen [::]:8080 default_server; server_name sub.domain.com; return 404; # managed by Certbot } -
Function save() doesn't work in Django. Why?
I want to save my form in database, but save() doesn't work. When I do this, error wasn't been. views.py def comments(request): comments = Comment.objects.all() form = CommentForm() context = {"comments": comments, "form": form} if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.avtor = request.user comment.save() return HttpResponseRedirect(reverse('comment')) else: context["form"] = form return render(request, "home/comments.html", context) else: return render(request, "home/comments.html", context) And models. So, I think problem yet in views.py models.py class Comment(models.Model): Text = models.TextField(verbose_name='Text') date = models.DateTimeField(default=timezone.now, verbose_name='date') avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE) def __str__(self): return 'Comment {} at {}'.format(self.avtor, self.date) class Meta: ordering = ["-id"] forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ("Text",) -
I'm getting "social_core.exceptions.AuthForbidden: Your credentials aren't allowed" error in Django python-social-auth/social-auth-app-django
I am using social-auth library to authenticate user with OAuth2. I can authenticate user with accessToken and check infos included in this token. The token is valid. The problem appears in line: user = self.backend.do_auth(access_token=access_token) And I get: "social_core.exceptions.AuthForbidden: Your credentials aren't allowed" This is part of my settings file: SOCIAL_AUTH__OAUTH2_WHITELISTED_DOMAINS = ["localhost"] AUTHENTICATION_BACKENDS = ( "social_core.backends.facebook.FacebookAppOAuth2", "social_core.backends.facebook.FacebookOAuth2", "social_core.backends.google.GoogleOAuth2") I checked also secrets keys and they seem to be good, because I am able to validate token. Thank you in advance! -
Django for loop template tag made using CBV
I am trying to make a simple blog. One of my blog pages displays all of the blog posts on the website. I know I need to use a for loop but I do not know what to put in for the variables. All of the tutorials I have seen have used function-based views and I am using CBV. Help would be much appreciated. all_posts.html {% extends "base.html" %} {% block content %} <div class="container"> <h1>Blog Posts</h1> </div> <div class="container"> {% for in %} {% endfor %} </div> {% endblock %} Views.py from django.shortcuts import render from django.views import generic from . import models from django.contrib.auth import get_user_model User = get_user_model() from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class create_blog_post(generic.CreateView, LoginRequiredMixin): model = models.Blog_Post template_name = 'blog_app/creat_post.html' success_url = '/' fields = ('post_title', 'blog_content', 'files') class view_blog_post(generic.ListView): model = models.Blog_Post template_name = 'view_post.html' class delet_blog_post(generic.DeleteView, LoginRequiredMixin): model = models.Blog_Post template_name = 'delete_post.html' class all_blog_posts(generic.ListView): model = models.Blog_Post template_name = 'all_posts.html' modles.py from django.db import models # Create your models here. class Blog_Post(models.Model): slug = models.SlugField(max_length=1000, editable=False, null=True) post_title = models.CharField(max_length=100, editable=True, blank=False, null=True) blog_content = models.TextField(max_length=10000, blank=False, editable=True, null=True) files = models.FileField(blank=True, null=True, upload_to=True) … -
Custom labels - Django auth user model - ModelForm
I'm trying to set custom labels for a UserCreationForm in Django. I've tried to follow the docs and searched on here. Only the first label changes via the labels dictionary I created. org.label at the top has been tested just to see if changes are made by setting a label outside of the dictionary. from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ class SignUpForm(UserCreationForm): email = forms.EmailField(required=True) org = forms.CharField(required=True) org.label = 'test org label' class Meta: model = User fields = ["username", "email", "org", "password1", "password2"] labels = { "username":_("xx-Username"), "email":_("xx-Email"), "org": _("xx-Organisation"), "password1":_("xx-Password"), "password2":"xx-Confirm Password" } The output I get is linked as an image. https://i.stack.imgur.com/7kGUY.png Many thanks. -
Django test - global variable from another script is not defined
I've been trying to run a second script from within the main one called by django's manage.py test. However, I'm getting this error: File "<string>", line 254, in <module> File "<string>", line 61, in login NameError: name 'driver' is not defined First, the test.py that runs during the manage.py test: import sys from django.contrib.staticfiles.testing import StaticLiveServerTestCase #https://docs.djangoproject.com/en/3.1/topics/testing/tools/#testcase #LiveServerTestCase class TestReunioes(StaticLiveServerTestCase): fixtures = ['fix_core.json','users.json'] def testRun(self): exec(open("seleniumtest.py").read()) And the second script, seleniumtest.py: import traceback import sys from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys url = "http://localhost:3000" chrome_options = Options() chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--disable-gpu") driver = webdriver.Chrome(options=chrome_options) driver.get(url) driver.set_window_size(1700, 850) driver.implicitly_wait(20) def login(): user="teste" passwd="321" driver.find_element(By.NAME, "user").send_keys(user) #line 61 from the error driver.find_element(By.NAME, "passwd").send_keys(passwd) driver.find_element(By.NAME, "enter").click() # # Several other functions to test other parts # try: print("Starting test") login() #line 254 from the error except: traceback.print_exc() finally: driver.quit() It's confusing me because if I run the seleniumtest.py from the command line, it works fine. It also works fine when called from a python file that is literally just the exec(open("seleniumtest.py").read()) . The error is only happening when called from the django test. I know it's something … -
Hi guys! simple error with AUTH_USER_MODEL
I created a User model in apps.accounts.models, added it to installed_apps specified it as AUTH_USER_MODEL INSTALLED_APPS = [ 'apps.accounts' ] AUTH_USER_MODEL = 'accounts.User' and got an error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed this is probably due to the fact that accounts has not been registered, but When I write AUTH_USER_MODEL = 'apps.accounts.User' I get an error line 15, in make_model_tuple app_label, model_name = model.split(".") ValueError: Invalid model reference 'apps.accounts.User'. String model references must be of the form 'app_label.ModelName'. what should I do with this? if I enter from the app. then I get the error "split", if I don't drive apps. then I get the error "that has not been installed" any hint will be appreciated -
django-exiffield: can't upload picture due to different format of 'CreateDate' and 'DateTimeField'
I'm a Django newbie, I hope you could help me. I'm developing a photo gallery app, and right now I'm trying to implement EXIF data extraction. It's working pretty well with pictures that were uploaded before the model migration, however, whenever I try to upload a new picture, I get this error: ValidationError at /admin/picture/picture/add/ ['“2021:11:12 15:26:56” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] It looks like DateTimeField and EXIF's CreateDate use a different format: DateTimeField uses YYYY-MM-DD HH:MM, while EXIF's CreateDate uses YYYY:MM:DD HH:MM. Is there any way to solve this? Here's my picture model: from exiffield.fields import ExifField from exiffield.getters import exifgetter class Picture(models.Model): image = models.ImageField(upload_to=get_image_upload_path) [...] # METADATA created_on = models.DateTimeField(blank=True, editable=False, null=True) width = models.PositiveIntegerField(editable=False, blank=True, null=True) height = models.PositiveIntegerField(editable=False, blank=True, null=True) size = models.CharField(max_length=20, editable=False, blank=True, null=True) camera_make = models.CharField(max_length=20, editable=False, blank=True, null=True) camera_model = models.CharField(max_length=20, editable=False, blank=True, null=True) lens = models.CharField(max_length=20, editable=False, blank=True, null=True) iso = models.PositiveIntegerField(editable=False, blank=True, null=True) shutter_speed = models.CharField(max_length=20, editable=False, blank=True, null=True) latitude = models.CharField(max_length=20, editable=False, blank=True, null=True) longitude = models.CharField(max_length=20, editable=False, blank=True, null=True) exif = ExifField( source='image', denormalized_fields={ 'created_on': exifgetter('CreateDate'), 'width': exifgetter('ImageWidth'), 'height': exifgetter('ImageHeight'), 'size': exifgetter('FileSize'), 'camera_make': exifgetter('Make'), 'camera_model': exifgetter('Model'), 'lens': exifgetter('LensInfo'), 'iso': exifgetter('ISO'), … -
Django ck-editor can't add extra plugin
I am trying to add an extra plugin but I can't. When I am inspecting my console it's saying can't load the javascript file. Here is my code: error which I am getting in my console but I have youtube plugin in my plugins folder: Loading failed for the <script> with source “http://127.0.0.1:8000/static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=LAHF”. settings.py STATIC_ROOT = 'var/static' CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'extraPlugins': ','.join([ 'youtube', ]), }, } urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), ] models.py class Blog(models.Model): blog_title = models.CharField(max_length=255) blog_body = RichTextUploadingField(blank=True, null=True,) I also tried this but didn't work: blog_body = RichTextUploadingField( config_name='default', # CKEDITOR.config.extraPlugins: extra_plugins=['youtube'], # CKEDITOR.plugins.addExternal(...) external_plugin_resources=[( 'youtube', 'var/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js', )], ) -
KeyError '\ufeffMaterial VN #'
I'm running into an issue where my form data seems to be encoded (not sure which encoding), but when I try to use pandas to locate my column name it searches for '\ufeffMaterial #' instead of 'Material #'. I've tried using pd.read_csv(file, encoding='utf-8-sig') and tried (unsuccessfully) to encode/decode the column name. Any suggestions? The line that's throwing the error is in functions.py: custColData = oldDF.loc[:,string]. functions.py def mapData(company, hierarchy): oldDF = pd.read_csv(company.file, encoding='utf-8-sig') newDF = pd.DataFrame() if (company.needsMapping == "False"): pass else: columnMappings = RawDataColumnMapping.objects.filter(companyName = company) attributesDict = {} for columnMap in columnMappings: string = str(columnMap.custColumn).encode('utf-8').decode() custColData = oldDF.loc[:,string] if columnMap.columnMapping != COLUMNS.attributes: newDF[columnMap.get_columnMapping_display()] = custColData else: custCol = columnMap.custColumn.split('~') columnDict = dict(zip(custCol, custColData)) attributesDict.update(columnDict) newDF['attributes'] = (json.dumps(attributesDict)) models.py class RawDataColumnMapping(models.Model): companyName = models.ForeignKey(RawData, on_delete=models.CASCADE) custColumn = models.TextField() columnMapping = models.PositiveSmallIntegerField(choices=COLUMNS) def __str__(self): return f"{self.companyName.companyName}_{self.custColumn}_{self.get_columnMapping_display()}" views.py def applyPPTMapping(request, companyName): if (request.method == "POST"): form = ApplyPPTMappingForm(request.POST, companyName=companyName) if form.is_valid(): rawData = form.cleaned_data['companyRawData'] rawDataCompany = rawData.split('_', maxsplit=2)[-1] rawDataObj = RawData.objects.get(slugField=rawDataCompany) hierarchy = form.cleaned_data['companyHierarchy'] hierarchyCompany = hierarchy.split('_', maxsplit=2)[-1] hierarchyObj = RawData.objects.get(slugField=hierarchyCompany) df = mapData(rawDataObj, hierarchyObj) -
how to get non selected values from multiselectfield
I use multiselectfield for a model. with this model I show the user which choices they have made. but I also want to show (filter) the unselected (null) values below. is there someone who can point me to a function that works with multiselectfield to extract the null values ? thank you. -
Video streaming in react-native using custom API
I'm working on a react-native app using expo-av to show videos, and whne I put in source the uri: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4', from google samples, it acutally works, but if I try to put a uri for a video contained in my django media folder, the following error occur: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". How can I solve? Thank you -
Data is not submitting through Ajax is not Submitting
here is ajax code $('#form').on('submit', function(e){ $.ajaxSetup({ headers: { "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value, } }); $.ajax({ type : 'POST', url: "{% url 'HealthTest' %}", data: { first_name : $('#first_name').val(), deparment : $('#deparment').val(), Reg_No : $('#Reg_No').val(), Health_status : $('#Health_status').val(), dataType: "json", }, success: function(data){ $('#output').html(data.msg) /* response message */ }, failure: function() { } }); }); This form code {% csrf_token %}{{form.as_p}} when i press submit in my pages this error message pop up in console window enter image description here I Tried different solution but it is not working for me. I am new to this Thank in advance. -
Is there an efficient way to add a csv file with many columns to a Django model?
I have a data frame with over 150 columns that I want to add to my Django database. Everything I have seen online gives an example only using a couple columns and requires that you list each field that you want to use. Is there a way to create a model that inherits from the data frame columns and does this process more efficiently? -
How to dynamically construct a hyperlink using Django named url
In my Django application I am using an ajax function to send some field values, do some processing (in views.py) and in the event of some exception (data mismatch etc), trying to construct a url for the user to use and navigate to the intended page (for further activities). Now, in the event of the exception (as described above), I am sending a pre-configured exception message (var_err) and a url (var_err_url) that would be constructed into a hyperlink for the user to make use of. Presently I am using the following scenario: Passing the two variables as json data bits (to display message text and dynamically creating a hyperlink, respectively) to the template and using jQuery to display the message along with the hyperlink (as shown hereunder): $('#id_err_message').html(var_err + ' <a href=" ' + var_err_url + '">Check</a>'); My set up works if I pass the url (variable var_err_url) as shown below: '/movement/planning/tpt_tenders/create/' i.e. the complete path. What I am trying to find out is: Is there a way to, instead, pass (Django) url name and dynamically create the hyperlink to have the same effect as shown under (as is done in Django templates), i.e.: <a href="{% url 'tpt_tender_add' %}">Add Tpt … -
Django JWT auth without migration
I have 2 projects written by Django : 1- Authentication(P1) and my_API(P2). in P1 I use DRF-simplejwt and 'dj-rest-auth' to register,login,logout,reset password ,... for P2 I need authentication. My opinion is that JWT does not use database for checking access token so It does not need to connect my users db to P2. But now I have error saying that I should migrate auth_user for rest_framework_simplejwt. What should I do now for checking permissions of P2 end points? Thanks for your attention :) -
Using Django's cache to store a model property
I have an image model with a foreign key back to the parent model. class MyImage(models.Model): parent = models.ForeignKey(ParentModel, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='images') I am also using django-s3-storage to have these images served from a private S3 bucket. When I ask for the image url in a template using (this is a class based detail view, I also get the images in a class based list view): {% for image in object.images.all %} <img src="{{image.image.url}}" alt=""> {% endfor %} the value returned from url is a signed url and that's fine. I'd prefer not to make my bucket public. The problem is that this signed url is generated every time I get the url from the image model, which prevents the image from being cached in the browser as the signature changes on every request. This isn't ideal since these images will rarely change and I'd like them browser cached to reduce S3 costs. I am currently also using Django's built-in caching (in my case, I'm using database caching for the time being). The built-in caching will let me cache template fragments like so: {% for image in object.images.all %} {% cache 1440 object_image object %} <img src="{{image.image.url}}" alt=""> …