Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
no response when subclassing a class based view
I'm attempting to subclass the django-summernote view that is responsible for uploading files. The view that I want to subclass (SummernoteUploadAttachmeent) can be seen here: https://github.com/summernote/django-summernote/blob/master/django_summernote/views.py Within my new view, I want to run a check before the upload can happen (i.e. I want to ensure that the number uploads is less than a certain limit. ursl.py from .views import SummernoteUploadAttachmentwCheck url(r'^summernote/upload_attachment/$', SummernoteUploadAttachmentwCheck.as_view(), name='django_summernote-upload_attachment'), views.py class SummernoteUploadAttachmentwCheck(SummernoteUploadAttachment): def post(self, request, *args, **kwargs): user = request.user print(user) #once I'm able to get user, I will check a counter to ensure that it's under limit before allowing the rest of the function to execute. I'm getting the following error: Traceback (most recent call last): File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view jasonsproject.views.SummernoteUploadAttachmentwCheck didn't return an HttpResponse object. It returned None instead. [28/Jun/2020 16:36:51] "POST /summernote/upload_attachment/ HTTP/1.1" 500 20462 Thanks! -
How to serve Vue data from Django backend?
So I am trying to use Vue & Django with django-webpack-loader (not DRF), but I'm just getting stuck whenever I try to actually feed Vue data. I am just trying to convert a static Django template to a (.vue) Vue template but I'm not sure how Vue is meant to handle that data? I'm under the impression that you do something along the lines of this in the script tags: new Vue ({ data: function () { game: {{game}} } }); And then reference this with {{game.title}} etc in the main html of the Vue template, using Django {% verbatim %} tags so they don't interfere right? But this just doesn't do anything, Django doesn't give Vue anything and I just get error 'game:' is defined but never used and error 'game' is not defined. I'm just not sure where to go from here and I just need some sort of help. -
Deploying Django on IIS alongside PHP applications
Has anyone done this successfully? Any advice is appreciated. I am able to deploy Django applications on IIS through the use of a VM, running Windows Server 2012 R2. This is the setup we have at work, only with PHP applications running on the default website. I want to replace some of these PHP apps with Django apps, but I don't want to mess up any of the PHP apps in the process. On the VM I can get things working with WFastCgi and some handler configurations, but this is with nothing else existing on the Default Web Site. If I add the web.config file to wwwroot to handle the Django app as shown here: https://docs.microsoft.com/en-us/visualstudio/python/configure-web-apps-for-iis-windows?view=vs-2019 will it interfere with the PHP apps? Also I have been adding everything to wwwroot, but I know for Django you are supposed to have your app outside of this folder. Not sure how I could do that in a way that would allow certain PHP apps in wwwroot to remain and others to be replaced. -
What causes django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table
I am trying to set up an open-source project locally https://github.com/OpenUpSA/wazimap-ng but I am having issues running migrations for guardian https://github.com/django-guardian/django-guardian which is also open-source. Some of the info that I think might be helpful If I try to remove the constraint ALTER TABLE auth_permission DROP CONSTRAINT auth_permission_content_type_id_2f476e4b; I am receiving an error ERROR: constraint "auth_permission_content_type_id_2f476e4b" of relation "auth_permission" does not exist If I try adding the constraint using ALTER TABLE auth_permission ADD CONSTRAINT auth_permission_content_type_id_2f476e4b PRIMARY KEY(content_type_id,name);, I am receiving an error ERROR: relation "auth_permission_content_type_id_2f476e4b" already exists How can I resolve this? -
OperationalError at /register/
When I am trying to signup in django app on heroku, it's saying no such table: auth_user . I tried to run manage.py migrate -syncdb. It execute successfully but still the problem is same. I works perfectly in development environment. What can be done to fix this. -
how to create a user in djoser with is_staff and is_superuser equals true
How to create a user in djoser and make it is_superuser=true and is_staff=true? -
django sweetify(sweetalert) for alerts does not work
I am trying to implement sweetify(sweetalert js) for my form, my javascript knowledge isn't good. nothing shows after i click submit. i have added sweetify to my settings.py ,nothing has changed despite doing it. i even tried the sweetalert cdn and used an id with button before and it didn't work. am i missing something? html {% load sweetify %} {% sweetify %} <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Tweetspace</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css" /> </head> <body> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p> <![endif]--> <form method="POST" action="{% url 'homepage' %}"> {% csrf_token %} <div class="field"> <label class="label">Message</label> <div class="control"> <textarea class="textarea" placeholder="Enter tweet" name="tweey"></textarea> </div> </div> <div class="field is-grouped"> <div class="control"> <button type="submit" class="button is-link">Submit</button> </div> </div> </form> </body> </html> views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages import tweepy import sweetify # Create your views here. def home(request): if request.method == 'POST': … -
Not getting prompt to set up superuser on Django's auth system?
I'm following a tutorial that uses Django's authentication system to log in users and when the sqlite3 db is first connected to django and the command python manage.py syncdb (tutorial is from before syncdb was deprecated) is run, I don't get this same message in the command line: You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? I instead ran python manage.py makemigrations python manage.py migrate and this seemed to have set up the tables but then when I run: select * from auth_user; nothing is returned to me in the command line. How can I setup a superuser from command line and get encrypted password, etc? -
Django addConstraints raises a TypeError on Postgres
I have in models.py a model called FlashNews, that can either be tied to a Race, a League, or a FantasyTeam. I used Django's CheckConstraint (version 2.2.1). There's also a type column to ensure consistency. I want to guarantee that one and only one column is not null among race, fteam and league, consistently with type value. The sample code is as is: FlashNewsTypes = [ (1, 'Race'), (2, 'League'), (3, 'Fteam') ] class FlashNews(models.Model): race = models.ForeignKey(Race, on_delete=models.CASCADE, null=True, blank=True) league = models.ForeignKey(League, on_delete=models.CASCADE, null=True, blank=True) fteam = models.ForeignKey(FantasyTeam, on_delete=models.CASCADE, null=True, blank=True) type = models.IntegerField(choices=FlashNewsTypes, default=FlashNewsTypes[0][0]) class Meta: constraints = [ models.CheckConstraint( name="unique_notnull_field", check=( models.Q( type=FlashNewsTypes[0][0], race__isnull=False, league__isnull=True, fteam__isnull=True, ) | models.Q( type=FlashNewsTypes[1][0], race__isnull=True, league__isnull=False, fteam__isnull=True, ) | models.Q( type=FlashNewsTypes[2][0], race__isnull=True, league__isnull=True, fteam__isnull=False, ) ), ) ] The automatically created migration: class Migration(migrations.Migration): dependencies = [ ('myapp', '0055_flashnews'), ] operations = [ migrations.AddConstraint( model_name='flashnews', constraint=models.CheckConstraint(check=models.Q(models.Q(('fteam__isnull', True), ('league__isnull', True), ('race__isnull', False), ('type', 1)), models.Q(('fteam__isnull', False), ('league__isnull', True), ('race__isnull', True), ('type', 2)), models.Q(('fteam__isnull', True), ('league__isnull', False), ('race__isnull', True), ('type', 3)), _connector='OR'), name='%(app_label)s_%(class)s_value_matches_type'), ), ] This migration is successful on my dev env, which uses Sqlite backend. But, when executed with Postgres backend, it raises this error: Applying myapp.0056_auto_20200502_1754...Traceback (most recent call … -
Django translations: setting of LANGUAGE_CODE working - accept-languages not?
I'm trying to fix translations for a little Django project of mine. Current status is, that I can switch translations by setting LANGUAGE_CODE to different values. But I would like to switch translations by means of accept-language of browser - which does not seem to work. My suspicion is, that for some reason the middleware is not configured correctly. This is what I have set for middlewares: MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I would like to know how I could check it the middleware is doing it's thing correclty - and why it seems to ignore accept-language. Any hints on this are highly appreciated! -
Properly configure TrigramSimilarity and SearchVector for searching users
I have written a search function in order to do FTS on my user model however, I am having a hard time figuring out how to configure it in order to get similar results as well, for instance, if the username contains MOST character of the search query it should display it as well. for instance if I search for bob and there is a user with username bobuser13 it should be displayed as well. Currently, my search function is: def search(self, search_text): search_vectors = ( SearchVector( 'username', weight='A', config='english' ) + SearchVector( 'last_name' , weight='B', config='english' ) + SearchVector( 'first_name' , weight='C', config='english' )+ SearchVector( 'first_name','last_name', weight='D', config='english' ) + + SearchVector( 'bio', weight='E', config='english' ) ) search_query = SearchQuery( search_text, config=' english' ) search_rank = SearchRank(search_vectors,search_query) trigram = TrigramSimilarity( 'username', search_text ) + TrigramSimilarity( 'last_name',search_text ) + TrigramSimilarity( 'first_name',search_text ) qs = ( self.get_queryset() .filter(sv=search_query) .annotate(rank=search_rank, trigram=trigram, bs=Greatest('rank','trigram')) .filter(Q(bs__gte=0.1)) .order_by('-bs') ) return qs And my user model is: class Profile(AbstractUser): bio = models.TextField() sv = pg_search.SearchVectorField(null=True) objects = ProfileManager() class Meta: indexes = [ GinIndex(fields=['sv'],name='search_idx_user'), ] def __str__(self): return self.username def get_absolute_url(self): return "{}".format(self.slug) how can I configure this so that it also includes similar names as well? -
NGINX configuration help needed. IP address works. Domain name displays NGINX default configuration
I have an issue which has been driving me insane all weekend. I have deployed my Django Rest Framework API using Ubuntu / NGINX / gunicorn. The API works and can be seen when you visit the IP (http://213.219.38.17/). However, when I visit the site using my purchase domain (www.conorbaileyapi.xyz) the NGINX default page is displayed. I purchased the domain 'conorbaileyapi.xyz' from Namecheap and added the correct name server records and added the A Records to the Linode server. My Allowed hosts list in my Django project is as follows: ALLOWED_HOSTS = ['213.219.38.17', 'conorbaileyapi.xyz', 'www.conorbaileyapi.xyz'] My NGINX server block is as follows: server { listen 80; server_name conorbaileyapi.xyz www.conorbaileyapi.xyz 213.219.38.17; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/conor/api/django-rest-api/blog; } location / { include proxy_params; proxy_pass http://unix:/home/conor/api/django-rest-api/blog/blog.sock; } } Thanks you in advance for you help. Conor -
How to learn first Django? [closed]
I hope this question is soon gonna be closed as non-constructive. But I am asking this because I've had a lot of search on Google and stack-overflow but I didn't have a satisfying answer. All other questions like this have been asked years ago and as things are changing rapidly I though this was necessary. So what I am asking is what resources should I follow. I'm done with tutorial app and now I want to go further and master this beautiful framework but next the thing django's website tells me to go to is the documentation. But isn't reading the documentation a bit cumbersome task(Its like depth-first-search. You go deeper and deeper until you reach the end). I just want to know if there are any advanced tutorials aimed at django 1.6 and higher. Some screen-casts or some book(other than django-book which quite outdated, as they say on the first page) like ones of Android that take you through by making different apps. -
Installing mysql on Amazon Linux 2 AMI
I have a Django project and i have deployed it to Elastic Beanstalk Amazon Linux 2 platform. I'm trying to install mysqlclient and add it to requirements.txt file but when i deploy it, i'm getting an error such as; ERROR: Couldn't install package: mysqlclient Package installation failed... I also tried to add a mysql.config file to .ebextensions such as below; packages: yum: python3-devel: [] mariadb-devel: [] It didn't work. And then i tried the .config file below; packages: yum: libmysqlclient: [] but it didn't work either. How can i fix this issue? -
Django Tempus Dominus datetimepicker javascript is rendered to template but it's not triggering calendar
I'm trying to use Tempus Dominus datetimepicker widget in Django. I think I added everything documentation is asking for. Icon of calendar is rendering into the template, as well as the JS function. Unfortunately clicking on calendar does not trigger the calendar, and i know nothing about JS so I really don't know where to start. Here is my code: forms.py class CreateMeetingForm(ModelForm): class Meta: model = Meeting fields = '__all__' exclude = ('client',) widgets = { 'time': DateTimePicker(options={ 'useCurrent': True, 'collapse': False, }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, })} index.html <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> {% load static %} <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css"> {{ form.media }} <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> What is actually rendering to browser <div class="input-group" id="div_id_time" data-target-input="nearest"> <input type="text" name="time" required="True" id="id_time" class="form-control datetimepicker-input" data-toggle="datetimepicker" data-target="#id_time"> <div class="input-group-append" data-target="#id_time" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> function deferDateTimePicker_id_time() { if (window.jQuery && $.fn.datetimepicker) { $('#id_time').datetimepicker({"format": "YYYY-MM-DD HH:mm:ss", "icons": {"time": "fa fa-clock-o"}, "useCurrent": true, "collapse": false}); } else { setTimeout(function() { deferDateTimePicker_id_time() }, 50); } } deferDateTimePicker_id_time(); -
Django form validation does not validate image
I need validation Image field (requared) in form, but is not work. I do not get validation error in template. Image Form class ImageForm(forms.ModelForm): class Meta: model = models.Image fields = ['title', 'image'] name = forms.CharField(label='Title', max_length=100) image = forms.CharField(label='Image', max_length=100) def clean_title(self): title = self.cleaned_data.get("title") if not title: return forms.ValidationError("title is requared") else: return title def clean_image(self): image = self.cleaned_data.get("image") if not image: raise forms.ValidationError("No image!") else: return image view.py if form.is_valid(): instance = form.save(commit=True) instance.save() return ImagesListView(request) else: return render(request, 'images/create.html', {'form': form}) Tenplate <form action="{% url 'images:create' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <table border="0"> {{ form }} </table> <input class="btn bk-bs-btn-primary" type="submit" value="Загрузить изображение"> </form> -
Github Dev Test Prod Workflow
I am new to git and want to get organized with my codebase. I have 3 repos (in Django): Dev Test Prod I wanted to know if there was some kind of a standard workflow for the codebase. Specifically, should I make it so that merged pull requests to dev automatically push to test? Should I make it so that pushes to test automatically deploy on AWS? What are the standards at companies you've worked at? Thanks! -
Django import_export " object has no attribute 'has_errors' " error when manipulate csv file before import using inherited "import_data" function
I am using Django import_export to upload a csv file. Due to a large number of rows, I need to import only rows that contain new data so that it doesn't make needless database calls and cut down on import time. To do this I called import_data under my my ModelResource class in an attempt to provide an much smaller tablib dataset. class ModelResource(resources.ModelResource): def import_data(self, dataset, dry_run=False, raise_errors=True, use_transactions=None, collect_failed_rows=False, **kwargs): new_dataset = tablib.Dataset() # Do stuff with original data and return new dataset ... return new_dataset However I receive the following error: 'Dataset' object has no attribute 'has_errors' Full Trackback Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Program Files\Python36\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\import_export\admin.py", line 316, in import_action if not result.has_errors() and not result.has_validation_errors(): Exception Type: AttributeError at /admin/engine/mtg/import/ Exception Value: 'Dataset' object has no attribute … -
Can't upload multiple images in Django from react
Im sorry to ask this because there may be lot of tutorials for multiple file upload in django. but none of them clarified my doubts. Im new to Django please be patient with me. Below is my django codes: models.py class Upload(models.Model): file = models.FileField(upload_to='images/', default=False) urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_app.urls')), ] urls.py urlpatterns = [ path('image', UploadViewSet, name='image'), ] views.py class UploadViewSet(viewsets.ModelViewSet): queryset = Upload.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = UploadSerializer React class Design extends Component { state = { file: null } handleFile(e) { let file = e.target.files[0] this.setState({ file: file }) } handleUpload() { let file = this.state.file let formdata = new FormData() formdata.append('images', file) console.log('this one:', file) axios({ url: "http://127.0.0.1:8000/image/", method: "POST", data: formdata, } ).then(res => console.log(res)) } render() { return ( <div class="upload"> <h1>Upload Images</h1> <br /> <br /> <Link to="/"> <button class="btn btn-warning">Back</button> </Link> <br /> <br /> <br /> <div className="d-flex p-4 z-depth-2"> <input type="file" multiple name="file" onChange={(e) => this.handleFile(e)} /> </div> <br /> <br /> <br /> <button onClick={(e) => this.handleUpload(e)} class="btn btn-red">Upload</button> </div> ); } } export default … -
django search returns all entries upon double click
I created search tool within my website using some help from internet. Problem is when I double click on seach button it brings all entries available, but work if you type whatever you search for. Code in views.py is below. class SearchResultsView(ListView): model = Entry template_name = 'wpb/search.html' def get_queryset(self): # новый query = self.request.GET.get('q') object_list = Entry.objects.filter( Q(title__contains=query.upper()) | Q(link__icontains=query) ) return object_list Code for search.html is below: <ul> {% for entry in object_list %} <li> <a href="{{ entry.link }}">{{ entry.title }}</a> </li> {% empty %} <h4>Ничего не найдено.</h4> {% endfor %} </ul> Cuoldn't find anything similar in the internet. -
Django ModelChoiceField is not filled when editing
I have ProjectForm form in which one field is ModelChoiceField with foreign key to Company Model. Creating new record and saving is not a problem, but when I want to edit that record this field is empy (like if none company was selected, but in DB I can see it with correct selection), other fields are filled correctly. I want to avoid changing template code as much as possible so its generated by universal form template. ----- models.py ----- class Company(models.Model): name = models.CharField(max_length=250, unique=True) ... class Project(models.Model): company = models.ForeignKey(Company, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=250, blank=False) description = models.TextField() ... ----- forms.py ----- @parsleyfy class ProjectForm(forms.Form): company = forms.ModelChoiceField(label='Společnost', queryset=Company.objects.all(), required=False) name = forms.CharField(label='Název') ... ----- view.py ----- def edit(request, pk): context = {'form_url': reverse('projects:project-edit', args=(pk,)), 'form_type':'edit'} obj = get_object_or_404(Project, pk=pk) if request.method == "GET": form = ProjectForm(initial=obj.__dict__) else: form = ProjectForm(request.POST, request.FILES) if form.is_valid(): try: obj.update(**form.cleaned_data) except IntegrityError: errors = form._errors.setdefault("name", ErrorList()) errors.append(u"Toto jméno již existuje") else: return redirect(LIST_URL) # SUCCESSFULLY SAVED context['form'] = form return render(request, FORM_TEMPLATE, context) ----- template.html ----- <form role="form" action="{{ form_url }}" method="post" enctype="multipart/form-data" data-parsley-validate novalidate> {% include 'projects/reusable/form_template.html' %} </form> in which: {% elif field|input_type == 'Select' %} <div for="{{ field.label … -
How to open full version of the site that was built on Django?
I have my first website that is based on Django 3. It’s good when I open it using my PC, but when I use mobile phone, it opens as a mobile version and compresses all the visual content so it looks awful. How can I make it open as a full version? -
Django error creating user manager for AbstractUser
I have written a custom search for my user model using custom Manager however, I am getting the following error: user = UserModel._default_manager.get_by_natural_key(username) AttributeError: 'ProfileManager' object has no attribute 'get_by_natural_key' Below are my AbstractUser and Manager how can I resolve this issue? class ProfileManager(models.Manager): def search(self, search_text): search_vectors = ( SearchVector( 'username', weight='A', config='english' ) + SearchVector( 'first_name', 'last_name' , weight='B', config='english' ) + SearchVector( 'bio', weight='C', config='english' ) ) search_query = SearchQuery( search_text, config=' english__unaccent' ) search_rank = SearchRank(search_vectors,search_query) trigram = TrigramSimilarity( 'username',search_text ) + TrigramSimilarity( 'last_name',search_text ) qs = ( self.get_queryset() .filter(sv=search_query) .annotate(rank=search_rank, trigram=trigram, bs=Greatest('rank','trigram')) .filter(Q(bs__gte=0.35)) .order_by('-bs') ) return qs class Profile(AbstractUser): ''' Some of my user fields ''' objects = ProfileManager() Thanks in advance! -
Django: How to use caching
I have an application in which data get refresh at 8 o’clock in the morning, data comes from database. I don’t want my database hits every time as throughout the day data is same and stale. What is the best way to tackle this problem in Django. and is it ok that my database gets hit every time. Usage of my application can be 10000 clients per day. using mysql db. -
Redirect back to previous page django
I am building a django app for which one component is simple CRUD for some models. I have created add, edit, delete, view details and listing pages. I have given the buttons to edit and delete records on listing page as well as view details page. Since the edit buttons from listing page and inner details page use same views and templates, the success url can either link back to view details page or listing page. I would like to add code so that if user goes to edit page from view details then is redirect back to details page on success, but if the user goes to edit page from listing page then the user is redirected to listing page (also listing page has pagination so user should go back to page s/he was on.