Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static files resolving after collectstatic
I have run python manage.py collectstatic so I have copies of my static files in "/static" folder. But now Django uses files from /static/myapp/js/myapp.js, not from myapp/static/myapp/js/myapp.js what should I change to resolve myapp/static/myapp/js/myapp.js first? settings.py STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' -
What is the difference between "return my_view" and "return redirect(my_view)" and how to get a mixed result?
I have a home in which I have a form that I get some info from students to suggest them some programs to apply to. The home view is as below: def home(request): template_name = 'home.html' home_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some stuff return programs(request) else: my_form = MyModelForm() home_context.update({'my_form': my_form, }) return render(request, template_name, home_context) In the second view, I have the same form and I want this form to be pre-occupied with the information I entered in the home page. That is why in the above, I passed my POST request to programs view that is as below: def programs(request): template_name = 'programs.html' programs_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some other stuff else: my_form = MyModelForm() programs_context.update({'my_form': my_form, }) return render(request, template_name, programs_context) The drawback of this strategy (passing the POST request in the home view to the programs_view) is that the url in url bar does not change to 'example.com/programs' and stays as 'example.com' . I will have some problems including problems in pagination of the programs. The alternative is that I do this: def home(request): template_name = 'home.html' home_context = {} if request.POST: … -
System to allow multiple users to work on same workbook
I am trying to build a web app with the following flow: users upload excel files to the web app. The app saves the data into a database and performs calculations on it. Then the system will output a workbook from the calculated data that multiple users have access and edit on, through the web app. The users should be able to use certain functionalities that are found in excel such as VLOOKUP, SUMPRODUCT and so on. For now, I am thinking of using django for backend and Azure services for the system; Azure web app services for the web app itself and azure sql service for the database. However, I'm not sure if there's a platform where I can store the output files and also allow users to open the files in an Excel online-like structure and directly edit (and use other workbook functionalities like VLOOKUP) on it through the web app. I've looked into Azure blob storage and Azure Files service to store the output files, but I'm not sure how I can open and edit the file from the web app. Please let me know if such thing can be done. Any other recommendations will also be … -
Django do not ask user from database for request
In my Django project I have a public API endpoint built with Django Rest Framework's APIView. It does not need to know anything about the user. Still, Django automatically fetches the session and the user from the database. Is there a way to not do this since it causes two unnecessary DB hits? Here is the code: class TermListView(APIView): permission_classes = () authentication_classes = () def get(self, request, format=None): qs = Term.objects.all().only('original_word') return Response([term.original_word for term in qs]) -
Django - UnboundLocalError
I have a function in a view that I am using to upload CSV data and write to a DB. That part is working. But when I try to check if there was data updated or created, I am getting an error which reads "local variable 'created' referenced before assignment". The function in the view is as follows def bookings_upload(request): prompt = { 'order': "Please import a valid CSV file" } if request.method == "GET": return render(request, 'booking_app/importBookings.html', prompt) csv_file = request.FILES['bookings'] if not csv_file.name.endswith('.csv'): messages.error(request, "This file is not a .csv file.") return redirect('/booking_app/bookings_upload/') data_set = csv_file.read().decode('utf-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Bookings.objects.update_or_create( book_date=column[0], grower_number=column[1], bales_booked=column[3], sale_date=column[6], book_id=column[11], reoffer=column[12] ) ) if created: messages.success(request, "Bookings have been imported successfully") else: messages.warning(request, "No new bookings were imported. Please check/verify your csv file") context = {} return render(request, 'booking_app/importBookings.html', context) What am I missing? Any assistance will be greatly appreciated. -
Jquery notification on Django message reception
I am trying to display a notification on a Django page when a Django message is received, usually after posting a form. This is the code I've written in my Django template, in the beginning of the <body> : {% if messages %} {% for msg in messages %} {% if msg.level == DEFAULT_MESSAGE_LEVELS.INFO %} <p>Displays OK</p> <script type="text/javascript"> $(document).load(function(){ new PNotify({ title: 'Regular Notice', text: 'Check me out! I\'m a notice.', type: 'info' }); }); </script> {% endif %} {% endfor %} {% endif %} The "Display OK" is there, no notifications pop up however. The page is based on the octopus html/css template : https://github.com/FireflyStars/octopus which uses the pnotify module for notifications (http://sciactive.com/pnotify/) The octopus template implements a button which triggers notifications. ui-elements-notifications.html: <button id="default-primary" class="mt-sm mb-sm btn btn-primary">Primary</button> examples.notifications.js : (function( $ ) { 'use strict'; $('#default-primary').click(function() { new PNotify({ title: 'Regular Notice', text: 'Check me out! I\'m a notice.', type: 'info' }); }); }).apply( this, [ jQuery ]); If I integrate the button html code on that same Django page, the notification displays correctly when clicking on the button, which leads me to believe that the libraries are correctly imported. I am not asking for debugging, … -
Problem with using the State variable in google api + Django
I'm trying to add the ability to save files to google disk to the django application. I took as a basis an example from the official documentation written in flask link import google_auth_oauthlib.flow from googleapiclient.discovery import build from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect import os os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' SCOPES = 'https://www.googleapis.com/auth/drive' cred = os.path.join(settings.BASE_DIR, 'credentials.json') Function for upload file: def file_to_drive(request, import_file=None): state = request.session['state'] if state is None: authorize(request) else: flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( cred, scopes=SCOPES, state=state) flow.redirect_uri = "http://localhost:8000/oauth2callback" authorization_response = request.build_absolute_uri() flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials service = build('drive', 'v3', credentials=credentials) file_metadata = { 'name': 'My Report', 'mimeType': 'application/vnd.google-apps.spreadsheet' } media = MediaFileUpload(import_file, mimetype='text/html', resumable=True) file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: %s' % file.get('id')) return (f"https://docs.google.com/document/d/{file.get('id')}/edit") And function for user authorization def authorize(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( cred, scopes=SCOPES) flow.redirect_uri = "http://localhost:8000/oauth2callback" authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') request.session['state'] = state return HttpResponseRedirect(authorization_url) urls.py path('oauth2callback', authorize, name='authorize'), path('to_drive', file_to_drive, name='file_to_drive'), In function file_to_drive searching for the value of the state parameter from the session, if it is not found, the authorize function is called. In the end, I get a message oauthlib.oauth2.rfc6749.errors.MismatchingStateError: (mismatching_state) CSRF Warning! State not equal in request and response. Error traseback looks like … -
ModuleNotFoundError: No module named 'admin'
I have this new remote job, where I had to clone all the code from a repository, and I have to make an export of the database from MySQL hosted in RDS. The first problem is that when I set up the configuration to start the app, it raise an error telling me this: Run Configuration Error: Broken configuration due to unavailable plugin or invalid configuration data. The other thing is that I already have the data dumped and set up in my local storage (the app works this way, is no longer using AWS Cloud) but when I try to do an python manage.py migrate , this error comes up... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\core\management\__init__.py", line 312, in execute django.setup() File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\apps\config.py", line 86, in create module = import_module(entry) File "C:\Users\Tony-App\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked … -
page boy found (404) notes.url
when i run the server this show up Page not found (404) Using the URLconf defined in notes.urls, Django tried these URL patterns, in this order: admin/ notes/ The empty path didn't match any of these notes urls.py from django.contrib import admin from django.urls import include , path urlpatterns = [ path('admin/',admin.site.urls), path('notes/', include('notes_app.urls')) ] notes_app urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$' , views.all_notes , name='all_notes'), url(r'^(?P<id>[\d]+)$', views.detail , name='note_detail') ] view from django.shortcuts import render from django.http import HttpResponse from .models import Note # Create your views here. ## show all notes def all_notes(request): # return HttpResponse('<h1> Welcome in Django Abdulrahman </h1>' , {}) all_notes = Note.objects.all() context = { 'all_notes' : all_notes } return HttpResponse (request , 'all_notes.html' , context) ## show one note def detail(request , id): note - Note.objects.get(id=id) context = { 'note' : Note } [enter image description here][1] return render(request,'note_detail.html' , context) -
Clarification needed for Including extra context to a serializer in Django REST Framework
According to: https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context I can write: serializer = AccountSerializer(account, context={'request': request}) and then serializer.data will look like: # {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'} but it doesn't say how I am to implement it. I mean it must be based on a call to rest_framework.reverse a bit like in this example: class CompleteTaskModelSerializer(rest_serializers.ModelSerializer): resultLocation = rest_serializers.SerializerMethodField() class Meta: model = TaskModel fields = ('id', 'resultLocation') def get_resultLocation(self, obj): return reverse('model', obj.model, request=request) but it won't acknowledge that there is anything called request in my method get_resultLocation. How is this magic supposed to work? -
Exporting django template data to excel and pdf
Respected developers. I need help with exporting data using template. I installed django-import-export and added it to admin panel now i can only export data from admin panel i want to know how can i export excel file using template example in this image.please also provide me doc links for exporting to pdf excel csv i will be thankfull to you. my admin.py from django.contrib import admin from import_export import resources from import_export.admin import ImportExportActionModelAdmin from.models import Business from.models import Add class AddResource(resources.ModelResource): class Meta: model = Add # class AddAdmin(ImportExportActionModelAdmin): # pass admin.site.register(Add) admin.site.register(Business) views.py def export_page(request): dataset = AddResource().export() print (dataset.csv) return render (request ,'export_page.html', ) this data is printing in console. -
Get list of all URL names in Django
I am putting together a template tag for active/currently visited links in a navigation bar so I can easily add the proper active CSS class to the link. I am have created code that works fine for either a mix of passed in urls with the same url-parameters included, but it does not allow me to pass in urls that have different params. {% make_active 'index' %} and {% make_active 'users' 1 %} could not be grouped together accurately as {% make_active 'index~users' 1 %} because I am using reverse() to see if the url exists. What I want is to just check the names from each of the url pattern files in my project and if the name exists, then I return the appropriate active class...but I cannot figure out how to simply grab the names. Is this possible, or can someone help with the code? @register.simple_tag(takes_context=True) def make_active(context, view_names, *args, **kwargs): """ Template tag that returns active css classes if a current link is active :param context: Context of view where template tag is used :param view_names: the view names passed into the :param args: :param kwargs: :return: """ print(args, kwargs) if not kwargs.pop('class', None): class_to_return = 'sidebar-item-active' … -
Django - Why db doesn't raise Exception when User.email is None?
I wan't User.email field to be required. I know that blank=True will make it required inside forms but I want to force this on the database level. The weird is that Django's User model has email with null=False by default so I don't understand why I can create a user just doing: User.objects.create(username='foo') And the database doesn't raise any error. Can someone explain? -
Displaying my current domain in my django template not working
I send html email to the users using the EmailMultiAlternatives and it worked also but the problem is in the email message the link is not working. But when I tried doing <a href="http://127.0.0.1{% url 'add_your_details' user.username %}"> then it worked perfectly as I wanted. I tried {{ request.META.HTTP_HOST }} {{domain}} also for domain and for protocol {{protocol}} template <a href="{{ request.scheme }}://{{ request.get_host }}{% url 'add_your_details' user.username %}" target="_blank">Add your details </a> settings ALLOWED_HOSTS = ['127.0.0.1'] -
How to create a form with sticky tag similar to that of adding tags to Stack overflow's in Django?
The feature on slack that allows you search for a user when you want to send a direct message and clip it, which is also similar to the way tags are added when filling out a question on StackOverflow is called what? How can one add this feature to a Django form? Can it be added to for a ForeignKey field or only a ManyToMany Field? -
Does django-cors-headers allow access from all origins to the admin site?
I am working on a Django app with DRF and I added CORS configuration using the django-cors-headers package recommended in the documentation. I will set the origin to be my client on the production. My question is, will the admin site be available to public access from all browsers with this setup? This is the production settings I am planning on using. # CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ['client origin'] I cannot test this atm because I am far from being ready for production. Thank you. -
Django test IntegrityError in fixture teardown
I started using the factory_boy package so I've set up some factories and wanted to test that the objects created don't raise any validation errors. Here's the mixin I'm using that basically takes every factory from a module, creates an instance, then tests that there are no errors from .full_clean(). The user fixtures that are loaded are 10 instances with IDs 1 to 10. class FactoriesTestCaseMixin: fixtures = [ 'user/tests/fixtures/user.json', ] module = None def test_factories(self): err_msg = '{name} caused errors:\n{errors}' factories = [ (name, obj) for name, obj in inspect.getmembers(self.module, inspect.isclass) if obj.__module__ == self.module.__name__ and not obj._meta.abstract ] for factory in factories: name = factory[0] instance = factory[1]() errors = None try: instance.full_clean() except ValidationError as e: errors = e self.assertTrue(errors is None, err_msg.format(name=name, errors=errors)) The mixin would be used like this from django.test import TestCase from order import factories class OrderFactoriesTestCase(FactoriesTestCaseMixin, TestCase): module = factories But I keep getting an IntegrityError (traceback below) after the test successfully passes in regards to fixture teardown and I can't figure out how to get around it so my tests pass with no errors. If I run the tests for each individual app there are no errors. I never get problems … -
failing to upload image files to my django database
I am new to Django Framework, I have created a html form to upload Post title, description and Image. Image is not uploading to the database. Please look into the code and suggest me how to fix this. Models.py class Post(models.Model): title = models.CharField(max_length=1000, unique=True) img = models.ImageField(upload_to='pics_post') desc = models.TextField() views.py def index (request) : posts = Post.objects.all() if request.method == 'POST' : if request.POST.get('newpost') == 'Submit': # post_title = request.POST.get('posttitle') # post_desc = request.POST.get('post_desc') # post_image = request.FILES['post_img'] # post = Post(title = post_title, desc = post_desc, img = post_image) # post.save() # return render(request, 'index.html', {'posts' : posts}) formdata = PostForm(request.POST,request.FILES) if formdata.is_valid(): formdata.save() return render(request, 'index.html', {'posts' : posts}) else : pass return render(request, 'index.html', {'posts' : posts}) else : pass else : return render(request, 'index.html', {'posts' : posts}) HTML form <form action="#" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control newpost" name="posttitle" placeholder="Post Title" id="posttitle" required> </div> <div class="form-group"> <input type="text" class="form-control newpost" name="post_desc" placeholder="Post Description" id="postdesc" required size="100" required> </div> <div class="form-group"> <input type="file" class="newpost" name="post_img" id="postimage" accept=".png, .jpg, .jpeg"> <p class="form-text text-muted">Only png and jpg allowed</p> </div> <button type="submit" class="btn btn-primary" name='newpost' id="commentsubmit" style="float: right;" value="Submit">Submit</button> </form> The commented part in the … -
The function stops working after adding the redirection. Ajax, Django - progress bar
I added a progress bar when uploading the file according to this tutorial in my Django app. Everything worked fine but when I try to change the 'alert' in my ajax file to refresh or redirect to another page, the bar stops working. For example i change this: success : function() { alert('File uploaded!'); For this: success : updatePage; I see this message on my command line after uploading form (but everything is saved correctly in the database): Exception happened during processing of request from ('127.0.0.1', 50954) Traceback (most recent call last): File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 717, in __init__ self.handle() File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] My file upload.js $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); var formData = new FormData($('form')[0]); $.ajax({ xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { console.log('Bytes Loaded: ' + e.loaded); console.log('Total Size: ' + e.total); console.log('Percentage Uploaded: ' + (e.loaded / e.total)) var percent = Math.round((e.loaded / e.total) * 100); $('#progressBar').attr('aria-valuenow', percent).css('width', … -
Django rest framrwork Nested Serializer's fields not appearing in parent serializer
In my Django app (using drf), I've modified my model's serializer to get the front-end's desired input, but I'm having zero luck trying to nest this serializer inside another one. I've tried creating a field of the model with the to_representation method and putting a get_photos method, none of which amounted to anything. # models.py class Photo(models.Model): photo = models.OneToOneField(RawPhoto, related_name='contest_photo', on_delete=models.CASCADE) thumbnail_size = models.OneToOneField(PhotoSize, related_name='contest_photo', on_delete=models.CASCADE) thumbnail_url = models.TextField(verbose_name='thumbnail_url') class Meta: verbose_name = 'Contest Photo' @property def get_photo_src(self): return settings.MEDIA_URL + self.photo.image.name @property def get_thumbnail_url(self): # dont forget to add cache if len(self.thumbnail_url) == 0: file_name = self.get_photo_src last_dot = file_name.rfind('.') photo_name, photo_extension = file_name[:last_dot], file_name[last_dot:] self.thumbnail_url = photo_name + '_' + self.thumbnail_size.name + photo_extension return self.thumbnail_url # serializers.py class PhotoSerializer(serializers.ModelSerializer): thumbnail_height = serializers.ReadOnlyField(source='thumbnail_size.height') thumbnail_width = serializers.ReadOnlyField(source='thumbnail_size.width') src = serializers.ReadOnlyField(source='get_photo_src') thumbnail_url = serializers.ReadOnlyField(source='get_thumbnail_url') caption = serializers.ReadOnlyField(source='photo.caption') class Meta: model = Photo fields = ['src', 'thumbnail_url', 'thumbnail_height', 'thumbnail_width', 'caption'] class GallerySerializer(serializers.ModelSerializer): photos = PhotoSerializer(many=True) class Meta: model = Gallery fields = ['title', 'photos'] PhotoSerializer actually returns the full description of the object that I expect from it, but when I nest it inside GallerySerializer, it only shows thumbnail_url, which is the only field that is included in the model itself. … -
Django won't serve an image from MEDIA_URL
A beginner building a personal blog. Got a simple model with an ImageField. No matter what I try the Django won't serve an image. Judging by the console output in the Dev Tools it is looking for an image in the wrong folder. I don't know how to fix that. I tried setting up MEDIA_URL, MEDIA_ROOT and adding a urlpattern like it's being suggest here and here I have uploaded the picture via admin panel, its location is media/images/stockmarket.jpg. But for some reason the server is looking for an image here /blog/images/stockmarket.jpg Project name: 'wikb', 'blog' is an App: project_file_system models.py from django.db import models class Post(models.Model): title = models.CharField('Post Title', max_length=200) preview = models.CharField('Post Preview', max_length=400) thumbnail = models.ImageField('Post Picture', upload_to='images/', blank=True) view.py from django.shortcuts import render from django.http import HttpResponse from .models import Post def home(request): all_posts = Post.objects.all() hero_post = all_posts[0] context = {'hero_post': hero_post, 'all_posts': all_posts} return render(request, 'blog/home.html', context=context) HTML <div class="hero"> <a href="#" class="hero__link" style="background-image: url({{hero_post.thumbnail}})"> <article class="hero__article"> <h2 class="hero__heading">{{hero_post.title}}</h2> <p class="hero__preview">{{hero_post.preview}}</p> </article> </a> </div> settings.py MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" Global 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 = … -
How to use grater than and less than or equl in django filter query
I am trying to filter data where added in between from date and to date. but i'm getting Cannot resolve keyword 'date_gte' into field. this error how to resolve this issue from1 = request.POST.get('from') to = request.POST.get('to') result = qwerty.objects.filter(date_gte= from1, date_lte= to) print(result) result.save() -
required=False not working with update_or_create in ModelSerializer
I am creating an API where I get some data with user_id field. If given user_id exist in DB it update rest of the data else it will create new data. Here my code: serializers.py class DataUpdateSerializer(serializers.ModelSerializer): user_id = serializers.CharField(max_length=250) email = serializers.EmailField(required=False) first_name = serializers.CharField(required=False) last_name = serializers.CharField(required=False) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'user_id', 'balance', 'device_id', 'platform') def create(self, validated_data): data_update, created = User.objects.update_or_create(user_id=validated_data['user_id'], defaults={ 'first_name': validated_data['first_name'], 'last_name': validated_data['last_name'], 'email': validated_data['email'], 'balance': validated_data['balance'], 'device_id': validated_data['device_id'], 'platform': validated_data['platform'], } ) return data_update views.py class data_update(APIView): permission_classes = (Check_API_KEY_Auth,) def post(self, request): serializer = DataUpdateSerializer(data=request.data) if serializer.is_valid(): serializer.save() username = request.data['user_id'] User.objects.filter(user_id=username).update(username=username) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_204_NO_CONTENT) email, first_name and last_name are optional and can be blank in DB or in serializer. Problem: Everything is working fine but if I don't pass email, first_name or last_name, it gives error: key_error and if I provide these fields with blank value "", this give error cannot be blank -
How to fix error "invalid literal for int() with base 10: 'Independence' Django?
I am trying to import a list of questions in my multiple choice questions model using the import_export.admin method, I am to import, but the list does not get appended to my existing list of questions, instead it throws invalid literal for int() with base 10: 'Independence'. I have tried change the format of the csv file I am uploading from comma-separated Values to CSV UTF-8(Comma-delimited). It reduced the number of columns the errors came from, from two to one. my admin.py file: class MCQuestionAdmin(ImportExportModelAdmin): list_display = ('content', 'category', ) list_filter = ('category',) fields = ('id', 'content', 'category', 'figure', 'quiz', 'explanation', 'answer_order') search_fields = ('id','content', 'explanation') filter_horizontal = ('quiz',) inlines = [AnswerInline] my models.py file: class MCQQuestion(Question): answer_order = models.CharField( max_length=30, null=True, blank=True, choices=ANSWER_ORDER_OPTIONS, help_text="The order in which multichoice \ answer options are displayed \ to the user", verbose_name="Answer Order") def check_if_correct(self, guess): answer = Answer.objects.get(id=guess) if answer.correct is True: return True else: return False def order_answers(self, queryset): if self.answer_order == 'content': return queryset.order_by('content') # if self.answer_order == 'random': # return queryset.order_by('Random') if self.answer_order == 'none': return queryset.order_by('None') def get_answers(self): return self.order_answers(Answer.objects.filter(question=self)) def get_answers_list(self): return [(answer.id, answer.content) for answer in self.order_answers(Answer.objects.filter(question=self))] def answer_choice_to_string(self, guess): return Answer.objects.get(id=guess).content class Meta: verbose_name = … -
Declacre CSRF-Token in forms.py
I'm using Djangos CSRF-Token the way it's mostly described on the internet: MyFormPage.html <form method="POST"> {% csrf_token %} {{ form.as_p }} </form> But I wonder - is there a way to include it somehow directly in the forms.py?