Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import a class from models of another Django app
Django version 1.9.7. My current project structure is: project1 │ ├── manage.py │ ├── pipeline │ │ ├── config.py │ │ ├── __init__.py │ │ ├── models.py │ │ ├── linkage.py │ │ ├── urls.py │ │ ├── utils │ │ ├── views.py └── web ├── rocket │ ├── admin.py │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ ├── views.py ├── db.sqlite3 How to import Project class from project1/web/rocket/models.py into project1/pipeline/linkage.py? I can't move the Project class somewhere else. And I tried to import it several ways, no success. way 1 $ head linkage.py import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '../..', 'web/rocket')) from models import Project way 2 $ head linkage.py import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'web')) from rocket.models import Project way 3 $ head linkage.py from ....rocket.models import Project Every time I receive the ImportError: cannot import name Project error. -
Django Rest Framework permissions not being called
I'm currently converting all my views to generics, as I like how cleaner the code gets. I am trying to make my User detail view, like so: # User.views from Common import view_mixins, view_filters, view_permissions class UserDetail(view_mixins.IntOrStrLookupMixin, generics.RetrieveUpdateDestroyAPIView): queryset = Profile.objects.all() lookup_fields = ('user__pk', 'user__username') lookup_url_kwarg = 'userid' filter_backends = (view_filters.ResourceVisibilityFilter, ) permission_classes = (view_permissions.IsOwnerOrReadOnly, ) serializer_class = ProfileSerializer def update(request, *args, **kwargs): return Response('HI') def get_object(self): obj = get_object_or_404(self.get_queryset()) self.check_object_permissions(self.request, obj) return obj # Common.view_permissions SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class IsOwnerOrReadOnly(permissions.BasePermission): ''' Owner of object can GET, PUT, DELETE. Everyone else can GET. ''' def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): print('did you call me?') return ( request.method in SAFE_METHODS or obj.user == request.user ) So my issue is, the permission is never called. I can get the user just fine, but anyone can do PUT or DELETE on which I am trying to prevent. -
django set multiple allowed hosts
I'm trying to set multiple allowed hosts in django I have setting configured in production settings production.py as ALLOWED_HOSTS = env('DJANGO_ALLOWED_HOSTS') which I can then set on heroku with: heroku config:set 'DJANGO_ALLOWED_HOSTS' = 'www.example.com' However how can I add multiple hosts via this method? -
Django: TemplateDoesNotExist at /home/
I am trying to add a template which displays a ModelForm on my Django app's home page. I made a separate app within my project for the home page called home since it isn't static, but the template I'm using is living in the main templates directory used by my project right now. When I run my server and try to navigate to /home, I get the following error: TemplateDoesNotExist at /home/ {'form': <ActionCodeForm bound=False, valid=Unknown, fields=(action_code)>} Request Method: GET Request URL: http://127.0.0.1:8300/home/ Django Version: 1.9.7 Exception Type: TemplateDoesNotExist Exception Value: {'form': <ActionCodeForm bound=False, valid=Unknown, fields=(action_code)>} How do I fix this error? I have tried looking at other SO answers for TemplateDoesNotExist errors and saw that it has to do with the 'DIRS' setting but mine seems to be set up correctly so I don't know what would be causing the error. Here is the templates section of my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Here's the template (action_code_form.html): <form method="post" action=""> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit"/> </form> Here is home/views.py: from home.forms import ActionCodeForm … -
Save/Restore GroupResult with Celery in Django: None returned
I am trying to save and restore GroupResult object after running task in Celery. The group result ID is returned and saved as expected. When I am trying to restore GroupResult with it: print(smstask.celery_result_id) print(app.GroupResult.restore(smstask.celery_result_id)) I get (as example): 4780fc17-44d8-478f-a41a-e4333aaa03d4 None For the Celery backend I am using Djcelery. Can it be the cause of the problem? CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend' What else can you recommend to try? Thank you! -
TypeError when open object of django filefield
I want to make a button named 'count' to count the number of page of the uploaded pdf file. However, there is TypeError invalid file: How can I improve my code to tackle this error...? PS. I'm newbie in coding using django 1.10, and just want to make some little tool to make my life easiler :) Thanks in advance My Models from django.db import models from PyPDF2 import PdfFileReader class PdfFile(models.Model): file = models.FileField(upload_to='document/') num_of_pages = models.IntegerField(null=True) def page_count(self): pdf = PdfFileReader(open(self.file, 'rb')) self.num_of_pages = pdf.getNumPages() self.save() My Views def count(request, pk): pdf = get_object_or_404(PdfFile, pk=pk) pdf.page_count() return redirect('img_preview', pk=pk) -
Uploading Multiple Images in Django
I'm trying to upload multiple images in a django form. Until now I got this error InMemoryUploadedFile' object has no attribute 'get' in the code line imgform.save() that is inside views.py This is my code simplified: realstate.models from django.db import models class Property(models.Model): title = models.CharField() class PropertyImage(models.Model): property = models.ForeignKey(Property, related_name='images') image = models.ImageField() realstate.forms from realstate.models import Property, PropertyImage class AddPropertyForm(forms.ModelForm): model = Property fields = '__all__' class ImageForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ImageForm, self).__init__(*args, **kwargs) self.fields['image'].widget.attrs['multiple'] = True class Meta: model = PropertyImage fields = '__all__' realstate.views def add_property(request): if request.method == 'POST': form = AddPropertyForm(request.POST) files = request.FILES.getlist('image') print(files) if form.is_valid(): for f in files: imgform = ImageForm(f) if imgform.is_valid: imgform.save() form.save() return HttpResponse("image upload success") else: form = AddPropertyForm() imgform = ImageForm() return render(request, 'realstate/admin-property-add.html', {'form': form, 'imgform': imgform}) template <form action="{% url 'realstate:add-property' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.title }} {{ imgform.image }} </form> Debug says that the error happens with imgform.save, but I don't really know how to proceed because the solutions I had seen say something like this: files = request.FILES.getlist('image') for f in files: #Do something with f... But I don't know what to to with file in order … -
Django-Registration-Redux: overriding default form and success URL
I've got django-registration-redux working but when trying to use a custom form and setting a custom success_url, it does not do it. If I change the source code for the BaseRegistrationView then it will work, why is this happening? I believe I am overriding correctly. registration is at the top of my INSTALLED_APPS. I have migrated. forms.py from django import forms from registration.forms import RegistrationFormUniqueEmail class UserProfileRegistrationForm(RegistrationFormUniqueEmail): field = forms.CharField() URLs.py import logging logging.basicConfig(filename='example.log', level=logging.DEBUG) from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from registration.backends.simple.views import RegistrationView from myapp.models import UserProfile from myapp.forms import UserProfileRegistrationForm class MyRegistrationView(RegistrationView): logging.debug("Class initialised") success_url = '/test/' form_class = UserProfileRegistrationForm def register(self, form_class): logging.debug("Registering") new_user = super(MyRegistrationView, self).register(form_class) user_profile = UserProfile() user_profile.user = new_user user_profile.field = form_class.cleaned_data['field'] user_profile.save() logging.debug(user_profile) return user_profile def get_form_class(self): logging.debug("Getting form class") return UserProfileRegistrationForm urlpatterns = [ url(r'^', include('myapp.urls')), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^accounts/register/$', MyRegistrationView.as_view(form_class=UserProfileRegistrationForm), name="registration_register"), url(r'^accounts/password/change/$', MyRegistrationView.as_view(), name="auth_password_change"), url(r'^accounts/password/change/done/$', MyRegistrationView.as_view(), name="auth_password_changed"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The logging for "Registering" never gets hit and neither does the "Getting form class". -
I am trying to print a cart with prices in Django
When I pass the context, the other end doesn't seem to be able to use it, to make it simpler and give an example I will try passing all my products and simply make a list of all the product id's, it doesn't work, all I get is a blank page when I visit the page... views.py def cart(request): items = [1,2,3,4] template = loader.get_template("Cafe/cart.html") ip = get_client_ip(request) order = current_order.objects.order_by('id') products = product.objects.order_by('id') context = { 'order': order, 'products': products, 'items': items } return HttpResponse(template.render(request)) cart.html <head> {% load static %} {% load app_filters %} <link rel="stylesheet" type="text/css" href="{% static 'Cafe/stylesheet.css' %}" /> </head> <body> {% for product in products %} <a>{{product.id}}</a> {% endfor %} </body> models.py class product(models.Model): categories = ( ('HD', 'Hot Drink'), ('CD', 'Cold Drink'), ('Br', 'Breakfast'), ('Sa', 'Sandwich'), ('Ex', 'Extras'), ('Sp', 'Specials'), ) product_name = models.CharField(max_length=100) category = models.CharField(max_length=2, choices=categories, default=categories[0][0]) price = models.FloatField() I don't see a reason why this should not work as the same concept works on all other pages I have made, I could really do with a response asap, many thanks. -
AttributeError on super() call with Python3 only
I am in the process of migrating an old project from: Django 1.6 => Django 1.10.2 Python 2.7.3 => Python 3.5.2 It's a somewhat big project and obviously this takes a while, but all in all it's going better than I hoped for. There is one thing that I can't really grasp though. With the models: class MoodelManager(models.Manager): def __init__(self, variety=None, *args, **kwargs): super(MoodelManager, self).__init__(*args, **kwargs) self.variety = variety def qet_queryset(self): qs = super(MoodelManager, self).qet_queryset() if self.variety: return qs.filter(variety=self.variety) else: return qs def a_varieties(self): qs = self.qet_queryset() if self.variety: return qs.none() else: return qs.filter(variety=self.moodel.VARIETY_A) class Moodel(models.Model): VARIETY_A = 'a' VARIETY_B = 'b' VARIETY_C = 'c' VARIETIES = ( (VARIETY_A, 'A'), (VARIETY_B, 'B'), (VARIETY_C, 'C'), ) variety = models.CharField(max_length=1, choices=VARIETIES) objects = MoodelManager() a_varieties = MoodelManager(VARIETY_A) class Related(models.Model): moodels = models.ManyToManyField(Moodel) With the tables populated and all, if I do Related.objects.first().moodels.a_varieties() I get AttributeError: 'super' object has no attribute 'qet_queryset' on line qs = super(MoodelManager, self).qet_queryset(). I assume that this has to do with Python and not with Django and I 've read all about super in the docs, around the web and in several SO questions and answers, but still I cannot understand this. Two questions: Why is this not … -
cant pass multiple models to my DetailsView using generic views
I have tried passing Album objects and song objects to my DetailView trying to get the DetailView working with both Album models and Song model. But anytime I try deleting a song my code cant seem to get the Song.objects.all(). I get a cannot find a song object in query or something like that here are my url patterns: urlpatterns = [ /music/ url(r'^$', views.IndexView.as_view(), name='index'), # /music/album_id/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^register/$', views.UserFormView.as_view(), name='register'), url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'), #/music/album/2/ url(r'album/(?P<pk>[0-9]+)/$', views.AlbumUpdate.as_view(), name='album-update'), #/music/album/add/delete/ url(r'^album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delete'), #/music/album/album_id/add-song/ url(r'^album/(?P<pk>[0-9]+)/add-song/$', views.SongView.as_view(), name='song-add'), # /music/album_id/song/delete/ url(r'^album/song/delete/(?P<song_id>[0-9]+)/$', views.SongDelete.as_view(), name='song-delete'), views.py: class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): template_name = 'music/detail.html' model = [Album, Song] # context_object_name = 'all_songs' # def get_object(self, queryset=Song.objects.all()): # return queryset def get_queryset(self): return Album.objects.all() class AlbumCreate(CreateView): model = Album fields = ['artist','album_title', 'genre', 'album_logo'] class AlbumUpdate(UpdateView): model = Album fields = ['artist','album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:index') class UserFormView(generic.View): form_class = UserForm template_name='music/registration_form.html' #displays a blank form def get(self, request): form = self.form_class(request.GET) return render(request, self.template_name, {'form': form}) #process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user=form.save(commit=False) #cleand (Normalized) data username= form.cleaned_data['username'] password=form.cleaned_data['password'] user.set_password(password) user.save() … -
How to give a score for each user in django
i'm beginner in django and i have a problem in this project, my goal is to make each user give a score from 1-10 to eachother. My question is how can i make "granted_by" to give a score "nota" to "granted_to" excluding itself. I don't know how to write it in views and use it in the template. Before giving me a - for asking a stupid and easy question, please take a peak to my code. models.py from django.db import models from django.conf import settings VALUE = ( (1, "Nota 1"), (2, "Nota 2"), (3, "Nota 3"), (4, "Nota 4"), (5, "Nota 5"), (6, "Nota 6"), (7, "Nota 7"), (8, "Nota 8"), (9, "Nota 9"), (10, "Nota 10"), ) class Score(models.Model): granted_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=0) granted_to = models.ForeignKey(settings.AUTH_USER_MODEL, default=0, related_name="granted_to") nota = models.PositiveSmallIntegerField(default=0, choices=VALUE) views.py from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from django.shortcuts import render from pro1 import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import Punctaj def Login(request): next = request.GET.get('next', '/home/') if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(next) # render(request, … -
Log russian chars in apache2 error log
I am trying to log some russian words in apache2 error log file but instead of russian chars I get utf-8 chars. how can i solve this issue? thanks -
django - how can render form's inputs out of labels in template
when my form render will be displayed like this: <p> <label for="id_form-0-food_name_0"><input checked="checked" id="id_form-0-food_name_0" name="form-0-food_name" value="" type="radio"> (Nothing)</label> <label for="id_form-0-food_name_1"><input id="id_form-0-food_name_1" name="form-0-food_name" value="1" type="radio"> خوراک مرغ</label> <label for="id_form-0-food_name_2"><input id="id_form-0-food_name_2" name="form-0-food_name" value="2" type="radio"> خوراک لوبیا</label> <label for="id_form-0-food_name_3"><input id="id_form-0-food_name_3" name="form-0-food_name" value="3" type="radio"> فسنجون</label> </p> but i need inputs render out of the labels tag. like this: <p> <input checked="checked" id="id_form-0-food_name_0" name="form-0-food_name" value="" type="radio"><label for="id_form-0-food_name_0"> (Nothing)</label> <input id="id_form-0-food_name_1" name="form-0-food_name" value="1" type="radio"><label for="id_form-0-food_name_1"> خوراک مرغ</label> <input id="id_form-0-food_name_2" name="form-0-food_name" value="2" type="radio"><label for="id_form-0-food_name_2"> خوراک لوبیا</label> <input id="id_form-0-food_name_3" name="form-0-food_name" value="3" type="radio"><label for="id_form-0-food_name_3"> فسنجون</label> </p> my forms.py: class Reserve(ModelForm): food_name = forms.ModelChoiceField( queryset=Food.objects.all(), widget=forms.RadioSelect(renderer=RadioFieldWithoutULRenderer), empty_label="(Nothing)", # label='' ) class Meta: model = Reservation fields = ('food_name',) and form.html <form method="post"> {% csrf_token %} {% for form in formset %} <p> <input name="group1" type="radio" id="test1" value="" /> {{ form.food_name }} </p> {% endfor %} <button type="submit" class="btn btn-default">Submit</button> -
Split Django input field and store into separate rows of record
Here's what I am trying achieve but not sure how to make it happen. I am building a literature analytic tool. User will paste some text into a field, the system will split word by word into a database table one row for each word, and they have to be sequential. By doing so, later then we can edit and define the translation/annotation of each word. I am new to Django and hvn't figure out the whole logic behind it yet, but I am curious if it is achievable. First things first, from the tutorial I just been through from the official Django website, every field created equals to a "cell" in a database table, so what happens if I want to split the content in the input field and store them rows of data in a database table with an ID incremented to index the order of them? Second, if the above is achieved, when i need to add a word(record) in the middle of the database, like adding something in the middle of an array, is it achievable? -
Postgresql password authentication failed on changing git branch | Django
I working on django project,I am new to postgres. When I was working on origin branch there was no problem with connecting to the database. But on changing the branch, I am unable to connect to the database. Both branches have to same database configuration in settings.py, which is as follows DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'tsl', #I suppose this is the database name 'USER': 'admin',# and this is the role name 'PASSWORD': 'xxxxxxxx', 'HOST': 'localhost', 'PORT': '', } } -
Django url NoReverseMatch error
I have next url file urlpatterns = patterns('callboard', url(r'^createadv/', 'views.createadv', name='createadv'), url(r'^editadvert/(?P<adv_id>\d+)/$', 'views.editadvert', name='editadvert'), url(r'^advdetail/(?P<pk>\d+)/$', 'views.advdetail', name='advdetail'), url(r'^',ProductListView.as_view() , name='callboard'), url(r'^product/(?P<category>[0-9A-Za-z._%+-]+)', ProductListView.as_view(), name='category'), url(r'^product/(?P<category>[0-9A-Za-z._%+-]+)/(?P<subcategory>[0-9A-Za-z._%+-]+)', ProductListView.as_view(), name='subcategory'), url(r'^notes/', 'views.notes', name='notes'), url(r'^get_subcategory/(?P<category_id>[0-9]+)/$', 'views.get_subcategory', name='get_subcategory'), url(r'^get_attribute_form/(?P<subcategory_id>[0-9]+)/$', 'views.get_attribute_form', name='get_attribute_form'), ) When I put advdetail URL I have an error NoReverseMatch at /callboard/advdetail/38/ Reverse for 'subcategory' with arguments '('mototransport',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['callboard/product/(?P<category>[0-9A-Za-z._%+-]+)/(?P<subcategory>[0-9A-Za-z._%+-]+)'] Request Method: GET Request URL: http://127.0.0.1:8000/callboard/advdetail/38/ Django Version: 1.8.15 Exception Type: NoReverseMatch Exception Value: Reverse for 'subcategory' with arguments '('mototransport',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['callboard/product/(?P<category>[0-9A-Za-z._%+-]+)/(?P<subcategory>[0-9A-Za-z._%+-]+)'] At the same time createadv works normal. Please help me found, where is a mistake? -
display xml content in web page using django and xslt
I want to display content of an XML file in the browser using xslt and django the content should be displayed in an html table with row header and three rows of content, but when I open the page I get row header of html table only. where is the problem. This is my code. xml code <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="test.xsl"?> <data-xml> <limit type="integer">10</limit> <entries type="array"> <entry> <key>key1</key> <value type="integer">1</value> </entry> <entry> <key>key2</key> <value type="integer">2</value> </entry> <entry> <key>key3</key> <value type="integer">3</value> </entry> </entries> </data-xml> This is xslt code: <?xml version="1.0" encoding="utf-8" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html" indent="yes" /> <xsl:template match="/data-xml"> <html> <head> <title>XML data</title> </head> <body> <strong>Limit: </strong> <xsl:value-of select="limit"/> <table border='1'> <tr> <th>Key</th> <th>Value</th> </tr> <xsl:for-each select="entries/entry"> <tr> <td> <xsl:value-of select="key"/> </td> <td> <xsl:value-of select="value"/> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> the code used in django: def index(request): return render_to_response('task_manager/test.xsl',content_type='text/html') -
Place default app name in url - django
I'm learning Django, and so far I always use to place app name before URL's link. Now i have separate student and staff application. Once i logged in as student, my url, localhost:8000/student/ should be default whatever the links I am navigating after logged in should change after student/. which means localhost:8000/student/ should be static and followed by any dynamic primary keys. Same like for staff application. -
Can't send POST data
I need to send POST request from one Django app to another. The request arrives, but without POST data. Why is that? And how to send POST data properly? Sender part: def _request(path, identifiers=None, post_data=None, method=None): data = None try: url = urlparse.urljoin(settings.ETL_WEB_API_URL, path) if identifiers is not None: for o in identifiers: url += "/" + str(o) if post_data: url += "/" request = urllib2.Request(url, data=post_data) request.add_header("Content-Type", "application/json") request.add_header("X-ETL-Authorization", settings.ETL_WEB_API_KEY) if method: request.get_method = lambda: method result = urllib2.urlopen(request) data_str = result.read() if result.getcode() == 200: data = json.loads(data_str) else: logger.error("Unexpected response %s" % result) except Exception as e: logger.exception(e.message) return data post_data example: {"project_id": "nYhRTAmGkkHSlLr8BfPR", "project_name": "rocket-launch", "salt": "805b2892c16369275eerec4dd401f5f", ...} (Pdb) type(post_data) <type 'str'> Receiver part: @csrf_exempt def get_data(request, trust_id): if request.method == 'POST': pdb.set_trace() The arrived message: (Pdb) request.POST <QueryDict: {}> -
Django REST framework JWT checks user from database with every request
I'm using Django REST framework JWT library for authentication in my django application. And I thought the whole idea of using JSON Web Token Authentication was NOT having a database trip in every request. But it still retrieves user's data (which is stored in the token's PAYLOAD) from database per request. What am I doing wrong? -
webkit2png.py renders black areas in image
The image generated by webkit2png.py for the url: http://ottawa.ca/en/city-council/councillor-tobi-nussbaum renders black areas. image renders black I tried with 10 seconds of waiting time, enabled javascript feature etc. Here is the command: python ``pwd``/webkit2png.py -x 1024 768 -g 1024 768 --scale 300 225 http://ottawa.ca/en/city-council/councillor-tobi-nussbaum Why is this happening? python ``pwd``/webkit2png.py -x 1024 768 -g 1024 768 --scale 300 225 -w 10 http://ottawa.ca/en/city-council/councillor-tobi-nussbaum python ``pwd``/webkit2png.py -x 1024 768 -g 1024 768 --scale 300 225 -w 10 --feature javascript http://ottawa.ca/en/city-council/councillor-tobi-nussbaum -
Django view do nothing on form submit
I have a form whose submit should only be handled once. Any extra clicks on the submit button should do nothing, where nothing means also not interrupting the flow of the first submit's POST request, which redirects to a GET when it finishes. What (if anything) can I return from Django's View's post method to achieve this behavior? Returning an empty HttpResponse as suggested in some other related questions on SO seems to interrupt the browser and display an empty page, thus interrupting the GET redirect which I'd like the browser to wait for. Looking for a server-side solution here, not just javascript disable of the submit button. Also, I can't just redirect the user to the GET page immediately on the second submit, since the page shows a success status and I'm only interested in showing that once the handling of the first POST is complete, which may take a few seconds. -
How to define a function to return content of many to many field
I have user_tag = models.ManyToManyField(User, related_name='get_user_tags', blank=True, null=True) i wish to define a model function which would return me the id of all users selected in that many to many field something like def get_user_tag(self): -
Query not responding to order_by
I'm trying to order_by a query but i cannot seem to accomplish it, any help would be appreciated users = User.objects.filter(Q(groups__name=group)).distinct() This is the starting query i have tried many ways to make this work with the order_by method. But cant seem to get it working i am trying to order the query by the first_name in descending order. .order_by('-first_name'.desc()) Something like this? I get an error 'str' object has no attribute 'desc' I have tried to look this up but cant see it being produced in the context that i am using it so i cant relate to the answers