Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customize Create funciton in DRF viewset
I want to customize the user viewset i.e. when the user registers the user account was created as well. -
How to require non-admin login before accessing Wagtail admin login
I am working on a Django App that uses Wagtail and django-allauth. I am using a workaround from Allauth docs to take advantage of some Allauth's features which are lacking in vanilla Django Admin login. from django.contrib import admin from django.contrib.auth.decorators import login_required admin.site.login = login_required(admin.site.login) I am trying to do the same for the Wagtail Admin, but am having no luck so far. My difficulty might be because the Wagtail admin views are class-based - I don't think I can use method_decorator in this context. Any help or pointers are highly appreciated. -
How to adjust ChainedManyToManyField to populated field based on another field?
I'm trying to populate district based on the selected city in the admin page. I tried the ChainedManyToManyField, but when selecting a city, there is no districts in the dropdown menu! class District(Timestamps): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=100) class ListingPrice(MinimumListingPriceBase): city = models.ForeignKey("location.City", on_delete=models.CASCADE, null=True) district = ChainedManyToManyField( District, horizontal=True, chained_field="city", chained_model_field="city", auto_choose=True ) How to make it possible to select districts based on selected city in the admin page? -
unsupported operand type(s) for @: 'Q' and 'Q' in Django RestFramework
I am trying to make login api using django rest framework and while doing login api serilization I encounter this error "unsupported operand type(s) for @: 'Q' and 'Q'" inside validate function. I couldn't understand why this error came and help me to solve this This is my model.py file class User(models.Model): first_name=models.CharField(max_length=100, null=True) last_name=models.CharField(max_length=100, null=True) username = models.CharField(max_length=100, null=False,unique =True) email = models.EmailField(max_length=100, null=False, unique =True) # work_email = models.EmailField(max_length=100,unique =True) password = models.CharField(max_length=50, null=False) phone= models.CharField(max_length=100, null=True,unique =True) phone2=models.CharField(max_length=100, null=True,unique =True) is_login = models.BooleanField(null=True, default=False) is_verified=models.BooleanField(null=True) is_active=models.BooleanField(null=True) token = models.CharField(max_length=100, null=True, default="") user_type_id=models.ForeignKey(UserType, on_delete=models.CASCADE,null=True) created_at=models.DateField(null=True) updated_at=models.DateField(null=True) def __str__(self): return "{} -{}".format(self.username, self.email) and here is serializers.py file from django.db.models import Q, fields from django.db.models.base import Model # for queries class UserLoginSerializer(serializers.ModelSerializer): username=serializers.CharField() password=serializers.CharField() token=serializers.CharField(required=False, read_only=True) def validate(self,data): # user,email,password validator username=data.get("username",None) password=data.get("password",None) if not username and password: raise ValidationError('Detail not enter') user=None # if email is passed in username if '@' in username: user= User.objects.filter(Q(email=username) & Q(password=password)).distinct() if not user.exists(): raise ValidationError("User credintials are not correct.") user= User.objects.get(email=username) else: user=User.objects.filter(Q(username=username)@ Q(password=password)).distinct() if not user.exists(): raise ValidationError("User credentials are not correct.") user = User.objects.get(username=username) if user.is_login: raise ValidationError("User already logged in.") user.is_login = True data['token'] = uuid4() user.token = … -
Test Django validator with parameters
I want to test a custom validator for an ImageField that checks that the aspect ratio of the image is between the given parameters. The validator takes a min_aspect_ratio and a max_aspect_ratio parameter, and returns a validator function, which takes the image from the ImageField: def validate_image_aspect_ratio(min_aspect_ratio: int, max_aspect_ratio: int): """Checks that the proportions of an image (width / height) are what we expect.""" def validator(image): if image is None: return aspect_ratio = image.width / image.height error_message = _( 'Image\'s height proportion to its width should be between %(min_aspect_ratio)s and %(max_aspect_ratio)s. ' 'It was %(aspect_ratio)s.' ) % { 'aspect_ratio': "{:.2f}".format(aspect_ratio), 'min_aspect_ratio': min_aspect_ratio, 'max_aspect_ratio': max_aspect_ratio } if aspect_ratio < min_aspect_ratio or aspect_ratio > max_aspect_ratio: raise ValidationError( error_message ) return validator Here's how I am using the validator: image = models.ImageField( _('Image'), help_text=_('A default image will be used if this is not set.'), blank=True, validators=[validate_image_aspect_ratio(1.25, 1.35)] ) Now I want to test this method, for which I will give it two arguments for the aspect-ratio range, but how do I pass the image to it? The problem is not creating a mock image for the test, just how do I pass it to the function, since it is passed to the returned … -
How should I send input array from javascript to django views.py
I am trying to send an array from javascript function to views.py and after some calculations to array i want to display the array on the webpage -
Ajax returns whole HTML page in Django
I'm trying to implement a simple form using the bootstrap modal but whenever I submit the form the response I get is whole HTML page. The request is POST. I have tried almost all answers which are present on the StackOverflow but none of them worked for me. My Modal form code: <div id="alert-box"></div> <form id="ajax-form" autocomplete="off"> {% csrf_token %} {{contact_form|crispy}} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> This is my Ajax code: <script type="text/javascript"> const alertBox = document.getElementById('alert-box'); const msgForm = document.getElementById('ajax-form'); const name = document.getElementById('id_name'); const number = document.getElementById('id_phone_number'); const message = document.getElementById('id_message'); const csrf = document.getElementsByName('csrfmiddlewaretoken'); const handleAlerts = (type,text) => { alertBox.innerHTML = `<div class="alert alert-${type}" role="alert"> ${text} </div>` } const url = ""; console.log(csrf); msgForm.addEventListener('submit',e => { e.preventDefault(); const fd = new FormData(); fd.append('csrfmiddlewaretoken',csrf[0].value); fd.append('name',name.value); fd.append('number',number.value); fd.append('message',message.value); $.ajax({ type: 'POST', url: url, data: fd, cache: false, contentType: false, processData: false, enctype: 'multipart/form-data', success: function(response) { const sText = `${response.name}`; handleAlerts('success', sText) setTimeout(()=>{ alertBox.innerHTML = ""; name.value = ""; number.value = ""; message.value = ""; }, 5000); }, error: function(error){ handleAlerts('danger', 'oops..something went wrong') } }) }); </script> This the form which I want to submit. -
Django Static Files does not deploy on Google Cloud Bucket
I am deploying an Django App, which runs on google server but it does not load the static files, so that App does not load the css and images. I checked the bucket I created but there is no files in the bucket. Here is settings.py STATIC_URL = '/static/' STATIC_ROOT = "static" PRODUCTION = True if PRODUCTION: # Define static storage via django-storages[google] GS_BUCKET_NAME = env("GS_BUCKET_NAME") print(GS_BUCKET_NAME) STATIC_URL = "/static/" DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_DEFAULT_ACL = "publicRead" else: MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Here is app.yaml file. runtime: python38 handlers: - url: /static static_dir: static/ - url: /.* script: auto Here is urls.py. urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I deploy the app, it was done successfully. but the static files does not deploy into the bucket. As well I run this bellow command. python manage.py collectstatic I followed this tutorial. -
IndentationError: unindent does not match any outer indentation level (views.py, line 20)
enter image description here Tried every damn thing from changing indentation to spaces to writing a new file, this error is determined to not go from django.urls import path from . import views app_name="main" urlpatterns= [ path("",views.homepage,name="homepage"), path("register/", views.register, name="register") ] -
I want to fetch the data using api in flutter
I am trying to build freelancing type app. I am using flutter and for my backend data i created an api using django rest framework. Here is the models.py: class Package(models.Model): management_duration_choices = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ("9", "9"), ("10", "10"), ("11", "11"), ("12", "12"), ("13", "13"), ("14", "14"), ("15", "15") ) title = models.CharField(max_length=120) delivery_time = models.ForeignKey( DeliveryTime, on_delete=models.CASCADE, null=True) package_desc = models.TextField(null=True) revision_basic = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_basic") revision_standard = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_standard") revision_premium = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_premium") num_of_pages_for_basic = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_basic", blank=True) num_of_pages_for_standard = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_standard", blank=True) num_of_pages_for_premium = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_premium", blank=True) is_responsive_basic = models.BooleanField(default=False, null=True, blank=True) is_responsive_standard = models.BooleanField(default=False, null=True, blank=True) is_responsive_premium = models.BooleanField(default=False, null=True, blank=True) setup_payment = models.BooleanField(default=False, null=True, blank=True) will_deploy = models.BooleanField(default=False, null=True, blank=True) is_compitable = models.BooleanField(default=False, null=True, blank=True) supported_formats = models.ManyToManyField(FileFormats, blank=True) # For Logo Design provide_vector = models.BooleanField(default=False, null=True, blank=True) is_3dmockup = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_basic = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_standard = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_premium = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_basic = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_standard = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_premium = models.BooleanField(default=False, null=True, blank=True) # For Digital … -
What is a good way to proceed to store and use sensitive data in prod environment?
I have a django web app in a production environment hosted on a server. To store sensitive data I am using a .env file excluded from my git process stored on the server where my app is hosted. # .env file { "ENV_TYPE": "prod", "SECRET_KEY": "mysecretkey", "ALLOWED_HOSTS":[ "somewhere.com" ], "DEBUG": false, "STATIC_ROOT": "/somewhere/staticfiles", "DATABASES": { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "databaseName", "USER": "username", "PASSWORD": "myPassword", "HOST": "somewhereelse.com" } } } And in my app I get back data like this in setting.py for instance: # setting.py # Get back non secret env data such as DEBUG, ALLOWED HOSTS with open(os.path.join(BASE_DIR, '.env'), 'r') as f: env_data = json.load(f) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env_data["SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env_data["DEBUG"] ALLOWED_HOSTS = env_data["ALLOWED_HOSTS"] Do you believe this is a good way to proceed ? Indeed I still have somewhere on my server some passwords that are hard coded. -
Apache24 Production Server For Django React App: React Shows 403 Forbidden Error
I am trying to run a production server on an AWS EC2 instance (Windows) using Apache for a Django backend connected with a React frontend. When I test the app on Django's runserver everything works well, but currently, when I try to use it on Apache I am just seeing a blank screen. When I check the console it tells me that I don't have permission to access the react static files (403 forbidden error). In my attempts to fix this, I have run collectstatic, which has put all of the static files (including the react ones) on an S3 Bucket. This means that the Django pages (admin pages) are able to use the static files, but the React pages aren't accessing the files from the S3 bucket. I'm not sure if it is better to find a way to get my React app to use the static files from the bucket, or if I should just continue to find a way to get Apache to serve the static files. I know that the files are able to be found because it isn't a 404, but a 403, so it must be some problem with my configuration that isn't giving … -
I got error while creating virtual environment in django
while creating a virtual environment in Django I got site-package is not writable and that's why when i write command of Django-admin so i got error not found in external or internal can anyone how I solve this -
How to Iterate a list sent from React in Django
I want to iterate colors in Django, it should print first red then green # data from frontend react data = request.data print(data) <QueryDict: {'colors': ['red', 'green']}> result should be like this : red green -
How do i maintain a user cover uploaded image in fields whiles adding new images without it getting deleted in django
How do i get Django to store already uploaded cover image to a user without getting it deleted when a new image is uploaded, but simply replace it? I'm having a challenge trying to figure out how to maintain old cover images while adding new once to a user. what happens is that when i upload a new cover image it simply deletes the previous one from the database. Here is my cover image models: class AccountCover(models.Model): account = models.ForeignKey(Account,on_delete=models.CASCADE) cover_image = models.ImageField(max_length=255,upload_to=get_cover_cover_image_filepath,default=get_default_cover_image,) Here the view to upload cover image cover = AccountCover.objects.filter(account=account.id).first() if request.user: forms = CoverImageForm(request.POST, request.FILES,instance=cover, initial = {'cover_image':cover.cover_image}) if request.method == 'POST': f = CoverImageForm(request.POST, request.FILES,instance=cover) if f.is_valid(): data = forms.save() data.account = cover.account data.save() return redirect('account:edit', account.id) else: f = CoverImageForm() context['f'] = f -
Sending data from django app to the arduino
I have written an arduino sketch to turn on and off a light using serial port. I coded to send serial data using pyserial. It worked fine. The python script below worked fine. But the problem is when I implemented that in the django application. Everthing works fine sending data, return values everything works fine but it doesn't turn on the light. I checked return value for s.write("on".encode()) it is also same as of the python script but in django it doesn't turn on the light. **Code from Arduino Sketch** String command; void setup() { Serial.begin(9600); Serial.println("Type your command"); } void loop() { if(Serial.available()){ command = Serial.readStringUntil('\n'); if(command =="on"){ digitalWrite(7, HIGH); } else if(command == "low"){ digitalWrite(7, LOW); } } } **code from python script** import serial ser = serial.Serial() ser.baudrate = 9600 ser.port = 'COM5' ser.open() data = ser.readline(82) ser.write("on".encode()) print(data.decode("utf-8")) **code from django** import serial # Create your views here. @csrf_exempt def index(request): if (request.method=="POST"): giveCommand = ReadFromArduino(baudrate=9600, port = "COM5") res = giveCommand.writeData(commandData = "on") return HttpResponse(res) s = serial.Serial() s.baudrate = 9600 s.port = "COM5" s.open() ret = s.write("on".encode()) print(ret) s.close() return HttpResponse("Hello") # giveCommand = ReadFromArduino(baudrate=9600, port = "COM5") # res = giveCommand.writeData(commandData = "on") … -
How to make the django rest framework POST button work?
I have a model like this: class Ad(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) text = models.TextField() # Shows up in the admin list def __str__(self): return self.title A Viewset like this: class AdViewSet(viewsets.ModelViewSet): """ API endpoint that allows ad to be viewed or edited. """ queryset = Ad.objects.all().order_by('-created_at') serializer_class = AdSerializer I have made the router and the serializer that I didn't include here because I don't think it's needed to show my issue. In the Django Rest Framework in /api/ads/ I can see all my previous ads created using the django admin and below a form to post data which looks like this: When I click on the POST button of the form,it doesn't make a POST request it just reload the page. I can confirm it from the Firefox devtool and the server log, no POST request are made. So my question is this: how to make this POST button works as expected so I can check my serialiser and everything work as it should ? -
Shows ERROR 405 in browser and method not allowed in shell - Django
I'm building a website that has 2 user types. The registration forms works fine but the login form and the Add Products form gives HTTP 404 ERROR in the browser and shows method not allowed in the shell. Here's all the codes of the project: seller/forms.py def login_seller(request): if request.user.is_authenticated: return redirect('home') else: if request.method=='POST': logform = AuthenticationForm(data=request.POST) if logform.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None : login(request,user) return redirect('home') else: messages.error(request,"Invalid username or password") else: messages.error(request,"Invalid username or password") return render(request, 'Seller/login-seller.html', context={'logform':AuthenticationForm()}) seller/models.py from django.db import models from Accounts.models import CustomUser class SellerProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete= models.CASCADE) name = models.CharField(max_length= 90) email = models.EmailField(max_length = 90, unique = True) store_name = models.CharField(max_length = 30, unique = True) def __str__(self): return self.name products/models.py CATEGORY_CHOICES = [ ("ILLUSTRATION", "Digital Illustration"), ("EBOOKS", "eBooks"), ("PHOTOGRAPHS", "Photographs"), ("COMICS", "Comics"), ] class Products(models.Model): seller = models.ForeignKey(SellerProfile, on_delete = models.CASCADE) title = models.CharField(max_length = 255) product_category = models.CharField(choices = CATEGORY_CHOICES, max_length = 100, default = 'eBooks') description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2, default = 0.00) thumbnail = models.ImageField(upload_to = 'media/thumbnail/',null=True, blank = True) files = models.FileField(upload_to = 'media/product_files/', null = … -
Get list of linked objects(used as foreign keys) when deleting an object in Django
I wish to create an API that can be called from the frontend and displays the summary and linked objects to the object i want to delete( Just like in the Django admin delete view) The linked objects are deleted as cascade is being used in the model definition How can I do that? I tried overriding the delete model and the delete view but couldn't get the desired results. -
pop up at if condition in views.py in django
I want to show a pop-up instead of the httpresponse shown as below in views.py after satisfying the if condition - (below is section of code in views.py) if data['check_in'] > now and data['check_out'] > now and data['check_out'] > data['check_in']: #Check if the room is available if available_rooms is not None: if len(available_rooms) >= int(num_rooms_req): for i in num_rooms_req_lst: #Book the First available room # print(available_rooms[i-1]) booking = book_room(request, available_rooms[i-1],data['check_in'],data['check_out'],total_cost) return HttpResponse(booking) else: return HttpResponse('Only 1 rooms available in this category') else: return HttpResponse('All the rooms of this category are booked! Try another category!') else: return HttpResponse('checkin/checkout date in past or checkout date is prior to checkin date!') so in the above views.py code section - what would be the best way to show the return HttpResponse pop-ups or alerts (but alerts would take me to different html) - I don't want to navigate away from the parent html... -
Dynamic user creation in django
I'm creating web-app with the following users, National Director Regional Director Project Coordinator Agent Expected Outcome: A National Director should be able to create a Regional Director, a Regional Director should be able to create a Project Coordinator, and a Project Coordinator should be able to create Agents. Question: How should I make views and forms to accomplish such? #Models class User(AbstractUser): pass class National_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) class Regional_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) REGION = ( ('North', 'Northern Region'), ('East', 'Eastern Region'), ('West', 'Western Region'), ('South', 'Southern Region'), ) region = models.CharField(max_length=20, null=False, blank=False, choices=REGION) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) national_director = models.ForeignKey(National_Director, null=True, blank=True, on_delete=SET_NULL) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) class Coordinator(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) regional_director = models.ForeignKey(Regional_Director, null=True, blank=True, on_delete=SET_NULL) region = models.CharField(max_length=15, null=True, blank=True) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) … -
What do you think the pros/cons of the integration of Django and Vue.js? [closed]
Vue.js can handle SQL with node.js. Django can have Javascript. Integration of Django and Vue.js is more complicated than the above two ways. My question is what kind of situation is suitable for the Integration of Django and Vue.js. And if you could, give me some example of service of it. -
Is there a posibility to link 2 models in Django?
I'm trying to create a quiz web app , where u will enter the app and u will have 2 buttons: create a quiz , and solve a quiz. You can do it without needing to register. I've created the models, one for Quiz and one for Question and i've put an UUID primary key to the quiz so that i can use this unique id as an extension to my link to get to the quiz that contains the questions. My problem is this. After i create a quiz , i want to directly go to the create questions file regarding the created quiz. Becouse right now after i create the quiz, i need to separately go and create a question, then make a dropdown to select the quiz wich the question is for. [image1][1] [1]: https://i.stack.imgur.com/dr4iP.png [image2][2] [2]: https://i.stack.imgur.com/K5tFt.png [image3][3] [3]: https://i.stack.imgur.com/7GdcK.png -
how to show active page while using base template and bootstrap
base.html The below file is my base template, I'm extending this template in my other pages like index, profile, etc. now in base.html home is my active page and I have done this with help of bootstrap class active, help me that how I can use this active class for different pages to show them active. I'm using the Django framework for rendering templates. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Student Portal</title> </head> <body> <!-- nav bar start --> <nav class="navbar navbar-expand-lg navbar-light "> <div class="container-fluid"> <a class="navbar-brand" href="/">StudentPortal</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo02"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'signup' %}">signup</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'profile' %}">profile</a> </li> </ul> </div> </div> </nav> {% block content %} {% endblock content %} <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Option 2: … -
Can I modify the URLs Django uses for "View on site" admin links to override caching?
My site is behind a cache. I use Django's "View on site" functionality (eg. by defining a get_absolute_url method for each model), but when I make a change to an object and then click "View on site", I don't see the changes because the cache hasn't expired. I don't particularly want to do things like check the referrer header (eg. Django admin routes these URLs via a redirect like /admin/r/19/1653/, which I could test for) as this breaks my cache strategy (I don't currently cache based on referrer). I tried injecting a timestamp query parameter via JavaScript (eg. to send admin users to /some-django-url?ts=12345, which would bust the cache) but this doesn't work because of the above redirect step (eg. I can't "see" the final Django URL in the admin screen, just the /admin/r/ redirect). Does anyone have a good strategy for this?