Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin linking me to a template
When programming locally on my development server, the site is functioning as expected. But when I go to my production site, a handful of the links in mysite.com/admin link me to a random template that's extending my base.html, rather than the typical database/form UI. For example, I expect this: But instead, I am getting: Any help would be great. -
Set a time for when object to be posted in Django admin?
I want to implement a feature where you can select a date for when a post can go public in the Django admin. Is there a way we can set this in Django? What's the best practice to do this? -
Error on inspectdb model creation django
I am using django with mssql. I already have a existing database and want to create django model for the tables in that database. I followed this django book instruction for inspectdb. http://django-book.readthedocs.io/en/latest/chapter18.html When i enter the command python manage.py inspectdb > interface/models.py I get following error Traceback (most recent call last): File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 547, i n _execute_command recordset = self.cmd.Execute() File "<COMObject ADODB.Command>", line 3, in Execute File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 28 7, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Server Native C lient 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 6 2, in execute return self.cursor.execute(sql) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 647, i n execute self._execute_command() File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 558, i n _execute_command self._raiseCursorError(klass, _message) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 488, i n _raiseCursorError eh(self.connection, self, errorclass, errorvalue) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 103, i n standardErrorHandler raise errorclass(errorvalue) sqlserver_ado.dbapi.DatabaseError: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Se rver Native Client 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None) Command: SELECT * FROM [Attribute] where 1=0 Parameters: … -
'Welcome' message from Nginx shown when I run my wsgi Django project + Nginx + Gunicorn
I'm beginner in Django and I've finished my first project. I have an Ubuntu server in Digital Ocean and this is what I've done: My project nginx configuration file: server { server_name domain.com; access_log off; location /static/ { alias /opt/myenv/static/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } My project is located in /opt/myenv/myenv/ When I execute gunicorn myproject.wsgi it looks like it's running Listening at: http://127.0.0.1:8000 (1481) But when I access into my IP, I just see an Welcome message from Nginx. What is happening? (Sorry my bad english) -
How to filter a QuerySet to max members of each group in django?
The model is something like this: class Application(models.Model): application_id = models.IntegerField() version_id = models.IntegerField() # some other attributes where application_id and version_id together determine an Application entry, in that one application may have several versions, and an entry with the largest version_id is the application's current version. And the goal is to find the current versions of all applications. The SQL (in MySQL) is something like: SELECT * FROM application AS app WHERE version_id = (SELECT max(version_id) FROM application WHERE application_id = app.application_id); How to achieve this? Please note that the object here is to filter the QuerySet, rather than only fetching the largest version_id, which would be as simple as using a GROUP BY, or in django a values() followed by an annotate(). I'm interested in the other attributes of the current version as well. -
Is it possible to do arithmetic operation on OuterRef expression?
I'm building an Experience booking system in django and I've the following models. class Experience(models.Model): name = models.CharField(max_length=20) capacity = models.IntegerField() class Booking(models.Model): experience = models.ForeignKey(Experience) occupied = models.IntegerField() Each experience has a limited number of capacity and when user perform booking, it will be added to the Booking table with occupied number. Now how will I find the experiences which are not occupied completely? available_experiences = Experience.objects.all().exclude(id__in=Subquery(Booking.objects.filter(occupied__gt=OuterRef('capacity') - request_persons).values_list('experience', flat=True))) Here, request_persons is the number of required vacancy in an experience. This is not working and showing an error like 'ResolvedOuterRef' object has no attribute 'relabeled_clone'. Is it possible to do arithmetic operation on OutRef() expression like F()? Without adding request_persons, the above code works. Why it is not possible to add a value to the OutRef() expression? NOTE: My actual code is much complex one and it will be really great to get an answer without modifying the entire structure of the above code. -
Django 1.11: Issues with utf8 writing to file on windows
I am trying to write some text into a file with data from django objects (CharField) and some formatting. The problem is with accentuated characters (é in the example below). On Linux I have no problems. However, on windows 7, I am getting extremely confusing behaviours. This (open call without encoding): from usermod.models import User user = User.objects.get(pk=134) with open('test.txt', 'w') as fout: fout.write(user.birth_place + ',') fout.write('Séoul') fout.close() produces: SxE9l,Séoul while this (open call with encoding): from usermod.models import User user = User.objects.get(pk=134) with open('test.txt', 'w', encoding='utf8') as fout: fout.write(user.birth_place + ',') fout.write('Séoul') fout.close() which produces: Séoul,Séoul Of course, the expected result is: Séoul,Séoul and this is what I get on Linux with the same database. So the weird thing is that each of those options gets different parts right and wrong. In one case the ORM retrieved value is wrong. In the other it is the string object created in the source code that is wrong. I can't find a way to get both right. All the files are encoded in UTF8 (as reported by notepad++). The python version is 3.5.4 The MySql database has all encodings in UTF8 and an SQL query on the user table shows the … -
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details
Had a problem running locally project! Maybe problem with virtual environment? settings.py: import os import dj_database_url INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap_pagination', 'main', ] if os.environ.get('DEBUG', False): INSTALLED_APPS += ['django_extensions'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'main.middleware.DeviceAuthMiddleware', ] WSGI_APPLICATION = 'cl.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases if os.environ.get('DEBUG', False): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } else: DATABASES = { 'default': dj_database_url.config(), } PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) DATAMUSE_URL = 'https://api.datamuse.com/words?sp=' I got the error message when trying to python manage.py runserver or python manage.py migrate. Here is the screen for the error: -
Django page for selecting model instances and adding them to a list
I am a beginner with Django, and my JS/HTML/CSS knowledge is intermediate. I have two models defined in models.py: One model Product that has some basic descriptive Fields (name, description, ...), and another model Category, that has a ManyToManyField products. I want to build a page where a user can select Products with checkboxes, and then add them to a category by pressing an "Add" button. Upon pressing, what should basically happen is: category.products.extend( selected_products ) # This only so that I know to which category a product has been assigned, not too urgent for product in selected_products: product.categories.append(category) Here is an image of what sort of page I am aiming for: https://i.imgur.com/BWs0eV0.png I am not asking for a full working example (unless there already happens to be one available of course). All I am looking for is some pointers on how to proceed creating this. I know how to create the list and the sidebar, but combining this with buttons per list element is new to me. Should the proposed page be essentially 1 giant form, and should I define it in forms.py? Should I be using the Django CheckboxInput widget? Is there a recommended structure for this type … -
Django Tutorial Help - "Not Found: /polls/index.html"
Working through the Django tutorial and have run into a problem I cannot figure out. Help would be appreciated. What am I missing here? Run this the tutorial a couple times now double checking all work, and code seems to match. Error: "Not Found: /polls/index.html" mysite/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] polls/templates/polls/index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} polls/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), # ex: /polls/5/ url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), # ex: /polls/5/results/ url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), # ex: /polls/5/vote/ url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] polls/views.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def index(request): return HttpResponse("Hello, world. You're at the polls index.") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're … -
ProgrammingError at / relation does not exist
I can not find answer in other places. (Sorry for asking again but) what is wrong? Did anyone have such an error? ProgrammingError at /register/ relation "user_user" does not exist LINE 1: SELECT (1) AS "a" FROM "user_user" WHERE "user_user"."userna... I extended user abstract model and error saying no relation When i extend user in sqlite3 no errors such this but postgre is full databse error class User(AbstractUser): social_username = models.CharField(max_length=100, null=True, blank=True) views.py def registration(request): if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) messages.success(request,'You were successfully registered %s' % user.first_name) return HttpResponseRedirect('/') messages.error(request, 'Something went wrong while authenticating') return render(request, 'project/register.html', {'form': form}) else: form = RegisterUserForm() return render(request, 'project/register.html', {'form': form}) settings.py AUTH_USER_MODEL = 'user.User' -
Django Change Profile Picture with a button
I'm currently trying to change the user profile picture using a simple button! Here is my work so far: views.py class UserProfileView(View): form_class = UpdateCustomUserPictureForm template_name = "accounts/user_profile.html" def get(self, request, *args, **kwargs): form = self.form_class(instance=request.user) context = { 'form': form, 'user_reviews': request.user.reviewed.all() } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): pass template <div class="image-container employee-image circle" style="max-width:150px; max-height:150px; margin:0 auto"> <img class="image" style="height:100%; width:100%; object-fit:contain" src="{{ user.profile_picture.url }}" alt=""> <div class="overlay"> <a class="text" style="text-decoration:none" href=""><font size="2rem">Modifica</font></a> </div> </div> forms.py class UpdateCustomUserPictureForm(forms.ModelForm): profile_picture = forms.ImageField( widget=forms.FileInput(attrs={'class': 'form-control'}), required=False ) class Meta: model = User fields = ('profile_picture',) def __init__(self, *args, **kwargs): super(UpdateCustomUserPictureForm, self).__init__(*args, **kwargs) self.fields['profile_picture'].label = "Immagine del profilo" How can I upload and change the picture by clicking on "Modifica"? This is the result i want to obtain: -
Web Frameworks: Frontend vs Backend
I'd like to know what characterizes/differentiates a frontend web framework from a backend web framework. For instance, Django is a backend framework while Angular is a frontend framework, but why? I can make an entire application using Django, so why is it not considered a frontend framework too? -
Template form does not render in Django
I have a form that I want to display. It looks like this: #the template to be filled with the form: #base.html {% load staticfiles %} <html> <head><title>{% block title %}{% endblock %}</title></head> <body>{% block content %}{% endblock %}</body> </html> The concrete page: #home.html {% extends 'base.html' %} {% block title %}Main{% endblock %} {% block content %} <h2>Home page</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} The VIEW #views.py def home(request): context = locals() template = 'home.html' return render(request, template, context) The URLs: from django.conf.urls import url from .views import home as home_view urlpatterns = [ url(r'^home/$', home_view, name='home'),] This does not draw the {{ form.as_p }} it only draws the submit buttonAny ideas why? -
Filter on variable of ManyToMany-field inside Django Template
I have a job-object and a content-object. A job object gets created when a user wants to retrieve a set of content-objects in exchange for credits. models.py: class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) class content(models.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) job_id_list_not_provided = models.ManyToManyField(JobId , related_name='JobIdFailed', blank=True) free_content = models.CharField(max_length=500, null=True, blank=True) paying_content = models.CharField(max_length=500, null=True, blank=True) For all content-objects part of the job, the JobId-object is added to the job_id_list - not keeping credit levels in mind. Different user can all run multiple jobs on the content objects. For too-big jobs exceeding the credit amount of the user, the content-objects that would push the credit level below zero, get also the JobID-object added to the job_id_list_not_provided field of the content-object. For a a specific user, we can retrieve the two sub-sets of found and not-found content-objects with following queries: views.py: found_results_list = results_list.filter(job_id_list_not_provided__user= None).distinct() not_found_results_list = results_list.filter(job_id_list_not_provided__user=request.user).distinct() My challenge: Result lists are over 100-objects in size, so I would like to use pagination to get a nice view on my page When not considering pagination, I could simply pass the 2 lists (found and not found) and loop over each list with a template … -
Django 2.0 - DateArchiveView date object for template
My app has ArchiveIndexView, YearArchiveView, MonthArchiveView and DayArchiveView. Except in ArchiveIndexView, I wanna add a Back link which will point back to its successor in all the views. So in the template of MonthArchiveView, I did it like this: <a href="{% url 'year_archive' date_list.0.date.year %}">Back</a> which would point back to YearArchiveView. But in DayArchiveView, there is no date_list attribute as of Django 2.0 documentation so how can I implement date object to be used in the template? -
django like button counting irregularly
I have a django application where I implemented a like button for posts posted on the blog. I recently discovered that when ever a like button is clicked by a registered user, the like increases exceedingly. Instead of the number of likes to get increased by 1 it increases by maybe 90+ and when the button is clicked agin for it to change to unlike it still increases so the like function becomes uneven. Below is my code for the like function Html {% with total_likes=obj.likes.count likes=obj.likes.all %} <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="#" data-id="{{ obj.id }}" data-action="{% if request.user in likes %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} like {% else %} unlike {% endif %} </a> JQuery <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function(){ $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "posts:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // … -
DRF annotate Count on many-to-many through table gives more occurrences than when you use _set.all().count()
I have these models: class Topic(BaseModel): name = models.CharField(max_length=60) public_name = models.CharField(max_length=60, blank=True, null=True) class Content(BaseModel): title = models.CharField(max_length=120) series = models.CharField(max_length=120, blank=True, null=True) season = models.CharField(max_length=45, blank=True, null=True) episode = models.CharField(max_length=45, blank=True, null=True) tags = models.ManyToManyField(tags_models.Tag, through='ContentHasTags') topics = models.ManyToManyField(topics_models.Topic, through='ContentHasTopics') class ContentHasTopics(BaseModel): content = models.ForeignKey(Content) topic = models.ForeignKey(topics_models.Topic) order = models.IntegerField(default=99) class Meta: unique_together = ('content', 'topic',) ordering = ('order',) The problem I have is that if I use the next function: @property def get_contents_count(self): return self.contenthastopics_set.all().count() In many cases I have 7 as a result (and is true), but when I use the annotate query like this for Django Rest Framework (in the viewset), it gives me like 28 results, some other topics have 5 contents using the _set.all().count(), but annotate gives me 10 as a result, and so on. queryset = models.Topic.objects.all().annotate( themes_count=Count('themehastopics') ).annotate( contents_count=Count('contenthastopics') ).annotate( tags_count=Count('topichastags') ) How is the right way to annotate the query with the Count correctly added? -
Django save multiple view variables
I'm trying to save URL parameters to my model. Already tried many things and currently getting argument error. Can't find proper documentation on this most likely because I am not sure what the proper search term is. All I need to do is save webhook POST to my URL. I will use @require_POST decorator to require POST only. Atm this is not the issue. The issue is simply saving the webhook. models.py from django.db import models from django.contrib.auth.models import User class Webhook(models.Model): clientAccnum = models.CharField(max_length=120, blank=True) clientSubacc = models.CharField(max_length=120, blank=True) eventType = models.CharField(max_length=120, blank=True) eventGroupType = models.CharField(max_length=120, blank=True) subscriptionId = models.CharField(max_length=120, blank=True) time_stamp = models.DateTimeField(blank=True) time_stamp_local = models.DateTimeField(blank=True) views.py def webhook(request): template_name = 'payment/index.html' hook = Webhook.save() hook.client_acc_num = request.GET.get('clientAccnum') hook.client_sub_acc = request.GET.get('clientSubacc') hook.event_type = request.GET.get('eventType') hook.event_group_type = request.GET.get('eventGroupType') hook.sub_id = request.GET.get('subscriptionId') hook.time_stamp = request.GET.get('timestamp') hook.time_stamp_local = timezone.now() hook.save() return render(request, template_name) -
Django admin TabularInline disable fields based on values
I am looking to disable fields in Django Admin TabularInline forms. My model has an optional end_date field which should, if set disable the input fields to avoid further modifications of values. Currently I tried modifying get_formset, but I am unable to get the values to finally disable fields using e.g.: formset.form.base_fields['contract_number'].disabled = True I am using the following code: class ServerLicenseInline(admin.TabularInline): model = ServerLicense autocomplete_fields = ('contract_number',) ordering = ('start_date', 'end_date') extra = 0 can_delete = False def get_formset(self, request, obj=None, **kwargs): formset = super(ServerLicenseInline, self).get_formset(request, obj, **kwargs) ... I was looking in obj and formset to find the values but without chance right now. Does someone have an idea how to achieve this? Thanks! -
django tables2 export to xlsx: How to set exported filename using FBV?
Django==1.11.7 django-tables2==1.10.0 tablib==0.11.2 Using function based views, how to set the exported filename? The tables 2 documentation gives a solution for class based views, but is not clear on function based views: http://django-tables2.readthedocs.io/en/latest/pages/export.html?highlight=function%20based%20views It mentions an "export_name", but where does this need to be set? Trying this: def export_payment_list(request): _table = PaymentTable4Export(Payment.objects.all().order_by('-payment_date')) RequestConfig(request).configure(_table) exporter = TableExport('xlsx', _table) return exporter.response('table.{}'.format('xlsx'), filename='my_test') ... results in an error: Exception Type: TypeError Exception Value: response() got multiple values for argument 'filename' Thank you for your help -
Fabric: executing makemigrations & migrate raises Secret Key Error
I'm working on a fabfile.py to stop repetition and deploy automatically. I'm using the prefix("workon vpenv"): provided by fabric but here is the problem: when running git pull everything works well, but when I run run("python manage.py makemigrations --settings=config.settings.production") I get the following error: [venuepark.com] run: python manage.py makemigrations --settings=config.settings.production [venuepark.com] out: Traceback (most recent call last): [venuepark.com] out: File "manage.py", line 22, in <module> [venuepark.com] out: execute_from_command_line(sys.argv) [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line [venuepark.com] out: utility.execute() [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 307, in execute [venuepark.com] out: settings.INSTALLED_APPS [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ [venuepark.com] out: self._setup(name) [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup [venuepark.com] out: self._wrapped = Settings(settings_module) [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ [venuepark.com] out: mod = importlib.import_module(self.SETTINGS_MODULE) [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/importlib/__init__.py", line 126, in import_module [venuepark.com] out: return _bootstrap._gcd_import(name[level:], package, level) [venuepark.com] out: File "<frozen importlib._bootstrap>", line 994, in _gcd_import [venuepark.com] out: File "<frozen importlib._bootstrap>", line 971, in _find_and_load [venuepark.com] out: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked [venuepark.com] out: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked [venuepark.com] out: File "<frozen importlib._bootstrap_external>", line 678, in exec_module [venuepark.com] out: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed [venuepark.com] out: File "/home/tony/vp/vp/config/settings/production.py", line … -
Django Admin Copying an Object and Prompting User for Updating Fields
I'm currently trying to set up an action where admins can copy an object. I was using the following code as an example for building out this functionality: from django.contrib import admin from course_tracker.course.models import SemesterDetails import copy def copy_semester(modeladmin, request, queryset): for sd in queryset: sd_copy = copy.copy(sd) sd_copy.id = None sd_copy.save() for instructor in sd.instructors.all(): sd_copy.instructors.add(instructor) for req in sd.requirements_met.all(): sd_copy.requirements_met.add(req) for attr_name in ['enrollments_entered', 'undergrads_enrolled', 'grads_enrolled', 'employees_enrolled', 'cross_registered', 'withdrawals']: sd_copy.__dict__.update({ attr_name : 0}) sd_copy.save() copy_semester.short_description = "Make a Copy of Semester Details" My problem is that I have a few fields that need to be unique, and so ideally I'd like to prompt the user with popups or something where they can add in titles or descriptions that are necessary for these unique fields. How can you add this in Django? Or would I need to utilize JavaScript for this? -
Django Rest Framework - authentication_classes by method in viewsets
I want to disable authentication on creation in my UserViewSet, so that even non authenticated user can create an account. I'm using django-oauth-toolkit to authenticate in my application, and I use their authentication class as default in my settings (which is great) I have tried to use the @authentication_class decorator (https://stackoverflow.com/a/39717881/5438372), but it doesn't seem to work with ModelViewSet And I also tried to override the get_authenticator method, in the same spirit as this : Django rest framework permission_classes of ViewSet method, but ViewSet.action doesn't seem to be available at authentication. How can I do this ? I there something wrong with my approach ? Here is my code : <models.py:> class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer permission_classes = (IsSelfOrStaffPermission, TokenHasReadWriteScope,) lookup_field = 'username' def get_queryset(self): current_user = self.request.user if current_user.is_staff: user_set = User.objects.all() else: user_set = User.objects.filter(username=current_user.username) query = self.request.query_params.get('q', None) if not query: return user_set return user_set.filter( Q(username__icontains=query) | Q(first_name__icontains=query) | Q(last_name__icontains=query) ) <settings.py:> REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } <permission.py:> class IsSelfOrStaffPermission(permissions.BasePermission): """ Permission to allow user actions on his own profile """ def has_object_permission(self, request, view, obj): return obj == request.user or request.user.is_staff -
Django ModelForm how do I change the label_suffix per each label
In Django ModelForm how do I change the label_suffix per each label. Some of them will have *, others not. (by default Django uses : )