Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django taggit-serializer not create tags in rest framework
here is my models.py class Post(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="post") title=models.CharField(max_length=128,null=True,blank=True) rate=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)],default=True,null=True,blank=True) # rating=models.IntegerField(null=True,blank=True) content=models.TextField(null=True,blank=True) review=models.CharField(max_length=250,null=True,blank=True) url=models.URLField(null=True,blank=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name="post_voters") tags = TaggableManager() in my serializers.py i have imported from taggit_serializer.serializers import (TagListSerializerField, TaggitSerializer) and here is the post serializer class Spost(serializers.ModelSerializer,TaggitSerializer): tags = TagListSerializerField() author=serializers.StringRelatedField(read_only=True) # likes_count=serializers.SerializerMethodField(read_only=True) # user_has_voted=serializers.SerializerMethodField(read_only=True) ## for string related field without displaying it as numerics , it displays the direct object of that object" # user=Scomments() class Meta: model = Post fields = ('id','title','rate','author','content','review','url','tags') def get_likes_count(self,instance): return instance.voters.count() def get_user_has_voted(self,instance): request=self.context.get("request") return instance.voters.filter(pk=request.user.pk).exists() but what issue i have been faceing right now is whenever i trigger a post request with tags the object is being created im getting that the object along with tags being created but when i see in the admin panel the tags part isnt being updated { "rate": 4, "content": "content", "review": "dsfdf", "url": "http://google.com", "tags": [ "django", "python" ] } this is the post request and in postman i can see the updated request { "id": 122, "title": null, "rate": 4, "author": "User", "content": "content", "review": "dsfdf", "url": "http://google.com", "tags": [ "django", "python" ] } but when i see the same thing in django admin panel and json list of all objects i … -
How to make django use two different databases based on debug
i want to be to use the simple db.sqlite3 on my local environment and use a postgresql in production. how can i configure the settings file to know which databse to use based on the value of DEBUG -
Django: Generate constant article profile
so far, as I was doing a blog in Django, I would generate all the data, link, only when we enter through such a thing path("/article/<slug:article_title>", ArticleView().as_view()) but this is not visible in google searches. I want to permanently generate this article so I can look it up on Google. -
Django Attribute Error - object has no attribute 'get'
I am trying to create a multiple file upload form using inlineformset factory. I followed the process defined in https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#django.forms.models.BaseInlineFormSet. I am getting following errow. Attached the views.py and model.py file. please help. Error: Request Method: GET Request URL: http://127.0.0.1:8000/tagging/UploadMultipleFile/1/ Django Version: 3.0.2 Exception Type: AttributeError Exception Value: 'UploadMultiFile' object has no attribute 'get' Exception Location: Python Version: 3.8.1 #MODELS.PY class UploadInputFile(models.Model): process=models.ForeignKey(Process,blank=False,on_delete=models.CASCADE,related_name="inputfile") inputfilepath=models.FileField(upload_to=user_directory_path, null=True) inputfilename=models.CharField(max_length=300,blank=True) multiplefile=models.BooleanField(blank=True,default=False) date_uploaded = models.DateTimeField(auto_now=True) def __str__(self): return(self.process.process_name) def get_absolute_url(self): return reverse("tagging:tagginghome") class UploadMultiFile(models.Model): process=models.ForeignKey(Process,blank=False,on_delete=models.CASCADE,related_name="process") batch=models.ForeignKey(UploadInputFile,blank=False,on_delete=models.CASCADE,related_name="multiplefiles") inputfilepath=models.FileField(upload_to=user_directory_path, null=True) inputfilename=models.CharField(max_length=300,blank=True) date_uploaded = models.DateTimeField(auto_now=True) def __str__(self): return(self.batch_id.process_id.process_name) def get_absolute_url(self): return reverse("tagging:tagginghome") # VIEWS.PY # upload Multiple files def UploadMultipleFile(request,batchid): batchid=int(batchid) pk=batchid getProcessAndBatch=UploadInputFile.objects.all().values().get(id=batchid) MultiFileUploadFormSet = inlineformset_factory(UploadInputFile,UploadMultiFile,fk_name='batch',fields=('inputfilepath','inputfilename')) if request.method=="POST": formset= MultiFileUploadFormSet(request.POST,request.FILES,instance=getProcessAndBatch) if formset.is_valid(): formset.save() else: formset= MultiFileUploadFormSet(instance=getProcessAndBatch) return render(request,"tagging/UploadInputFile_Form.html",{'pk':pk,'formset':formset}) -
unable to install mysqlclient to connect django to mysql db on my mac
I'm new to mac, python and django. This will be my second project. I use to have a django environment working on my old windows pc but, that also came with many weeks of struggle to get it working. Now I've been struggling through article after article on the web but, with absolutely no progress for 2 weeks. I just keep getting this issue..... (klsapp) normancollett@Normans-MacBook-Air klsapp % pip3 install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/normancollett/Documents/GitHub/klsapp/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/gy/lrnz57_x27z52f77rgshj80w0000gn/T/pip-install-nkn6549a/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/gy/lrnz57_x27z52f77rgshj80w0000gn/T/pip-install-nkn6549a/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/gy/lrnz57_x27z52f77rgshj80w0000gn/T/pip-wheel-658q_j90 cwd: /private/var/folders/gy/lrnz57_x27z52f77rgshj80w0000gn/T/pip-install-nkn6549a/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.6 creating build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb creating build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension … -
How Do I Group a Model Class with More then Two Levels of Subcategories?
How do you define a organized choice of a model class that have more then two levels in the named groups. I want to create a class so when I add a meteorites it goes into the proper classification but also inherits the top levels. For example a shergottites meteorite is also a differentiated meteorites, martian meteorites. differentiated meteorites martian shergottites I am self taught through basic Django tutorials and basic google search troubleshooting which has worked so till this. I am open to any solution, but was wondering whats the best practice for adding something with multiple nesting inside. Later this grouping will be import for sorting, searching and most functionality. I found this on Django project which is close to what I need but there are a few extra levels of organization. MEDIA_CHOICES = [ ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ] Below is what I am trying to do which two broad categories with 3 and 4 sub categories in each with up to two more subcategories. Here is NASA chart I am using for classification as a picture NASA Meteorite Classification Chart In … -
Microsoft Azure - App Service for containers (Docker problem)
i am trying to upload django app at microsoft azure using their solution app services for containers. The APP without docker is working perfectly, after i added docker it's working locally but when i use microsoft container registry and upload it to and then try to use their app for containers solution it doesn't work. I need some help in here: I created basic django restapiframework. Didn't add anything in there. After that i checked if it's working locally and it's working perfectly. After that i uploaded it on microsoft azure web app (not for cointaners) and it worked perfectly. After that i tried to add docker to my project and use microsoft azure web services for containers. Below is my docker code and commands i try to use for locally: DockerCompose: version: '3.7' services: web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate --run-syncdb && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - ./django_dashboard:/usr/src/django_dashboard ports: - 8000:8000 env_file: - ./.env.dev DockerFile: FROM python:3.6 # set work directory WORKDIR /usr/src # install dependencies RUN pip install --upgrade pip COPY requirements.txt /usr/src/requirements.txt RUN pip install -r requirements.txt # set work directory WORKDIR /usr/src/django_dashboard # set … -
Django Return 1 If Course Is A Paid Course
I want to be able to determine if a course is a paid course. If it is, return 1. A course can be any combination of Free, Monthly, or Yearly. Monthly and Yearly are paid and cost money. I tried doing a couple of things (template for loops) and using a paid function in my model and have not had luck with either one. Desired Result: If a course allows Monthly or Yearly access then return 1 Template Loops: {% for object in object.course.allowed_memberships.all %}{{object}}{% endfor %} FreeMonthlyYearly {% for object in object.course.allowed_memberships.all %}{% if object|stringformat:"s" != 'Free' %}1{% else %}0{% endif %}{% endfor %} 011 Models.py: class Course(models.Model): SKILL_LEVEL_CHOICES = ( ('Beginner', 'Beginner'), ('Intermediate', 'Intermediate'), ('Advanced', 'Advanced'), ) slug = models.SlugField() title = models.CharField(max_length=120) description = models.TextField() search_page_description = models.TextField() allowed_memberships = models.ManyToManyField(Membership) created_at = models.DateTimeField(auto_now_add=True) subject = models.ManyToManyField(Subject) skill_level = models.CharField(max_length=20,choices=SKILL_LEVEL_CHOICES, null=True) visited_times = models.PositiveIntegerField(default=0) thumbnail = models.ImageField(blank=True, null=True, max_length=255) thumbnail_alt = models.CharField(blank=True, null=True, max_length=120) @property def paid(self): print(self.allowed_memberships.all().exclude(membership_type='Free')) for x in self.allowed_memberships.all().exclude(membership_type='Free'): print(x) if str(x) in ('Monthly', 'Yearly'): return '1' else: return '0' class Lesson(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) description = models.TextField() transcript = models.TextField() … -
django Could not find a version that satisfies the requirement sweetalert2 (from versions: none)
I am using django 3.0.3, why i cant install sweetalert? does django supported sweetalert? ive tried also sweetalert and sweetalert2 -
Django View Runs 3 Times
I have a Django app that on one page, passes variables through the URL using Javascript to another page. The variables are then retrieved in a view function. The 'save_playlist()' function is being retrieved 3 times rather than simply once. I think it may have something to do with the way I'm passing variables or that I should have separate views for separate functions but as I'm rather new to Django and using APIs I'm not quite sure. In the first HTML page where the variables are appended to the URL, I have a button that when clicked runs this Javascript function: (The user has input a username which is retrieved from a form field) function spotifyButton(){ var spotify_username = document.getElementById("username").value; var playlist_ids = document.getElementsByClassName("song_id"); var url = 'http://127.0.0.1:8000/save_playlist/'; url += spotify_username + '/';//pass username for (var j=0; j<playlist_ids.length; j++){ //pass generated playlist var id = playlist_ids[j].textContent; url += id + '/'; } window.location.assign(url); } My urls.py is then set up to capture the variables in the url as the variable 'data': urlpatterns = [ path('', views.splash, name='splash'), path('home', views.home, name='home'), path('upload-data/', views.data_upload, name='data_upload'), path('playlist/', views.playlist, name='playlist'), re_path(r'^save_playlist/(?P<data>.+)$', views.save_playlist, name='save_playlist'), path('save_playlist/', views.save_playlist, name='save_playlist'), ] I have commented out where I … -
How to Redirect User in Django
Simply what I want is if user is Logged in don't let him enter the login page, just auto redirect him to the home page How to redirect user from HTML page(if authenticated/logged in)?? I tried using the following - html - code but didn't work {% if user.is_authenticated %} <meta http-equiv="refresh" content="0; url=/"> {%else%} <h1>there is a log in form here<h1> -
Choices prevent from making migrations
Django 3.0.4 def get_choices(): blank_choice = (None, '----') choices = [] # choices = [blank_choice] + [(str(item.id), str(item)) for item in YandexTextAdTemplates.objects.all()] return choices class CopyForm(forms.Form): ad_template = forms.ChoiceField(choices=get_choices()) I need choices in my form. Now the necessary string is commented out. If I return choices back, it will work. But it will not make migrations. (venv) michael@michael:~/PycharmProjects/ads3/ads_manager$ python manage.py makemigrations Traceback (most recent call last): File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "yandex_ads_yandextextadtemplates" does not exist LINE 1: ...ndextextadtemplates"."audience_yandex_pixel" FROM "yandex_ad... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/django/utils/functional.py", … -
Django- passing object in context for partial not working, but working in general view
I'm making a new Django app I can pass/access a variable in one view but not another (partial) view. The details: I have a partial for my top navbar, where I want to include a link to the 'person page' for the logged in user. In views.py, I pass along a QuerySet for the user in the context for both the top_nav and the person_index view, but I can only seem to access it when it's included for person_index. The person index view is set up like this: person_index.html extends base.html base.html includes the top_nav.html then the 'meat' of the view is in {% block content %} See views.py below: I grab the person the same way in top_nav and person_index. Interestingly, even if I don't pass it in context for top_nav, that partial can still "find" it when it's passed in context for person_index (the face_link partial works). But obviously I don't want to get/pass it for EVERY view, instead I want to do it once and pass it along to top_nav.html, but when I do so it's not found. views.py: def person_index(request): accessible_branches = get_valid_branches(request) this_user_person = get_user_person(request.user) person_list = Person.objects.order_by('display_name') # add this to limit list displayed: … -
How to pass values from foreign key to ajax calls with django model
I have a fairly simple model in Django: class TimeReport(ValidateModelMixin, models.Model): created_at = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(Person, on_delete=models.DO_NOTHING) year = models.CharField(max_length=9) TERM_CHOICES = [ ('winter', 'winter'), ('summer', 'summer') ] term = models.CharField(max_length=255, choices=TERM_CHOICES) ... class Person(AbstractUser): ... Now, I have a view that generates a template that makes ajax calls once the page is loaded. The ajax call that requests another view: def get_time_reports_api(request, year, term): if request.is_ajax(): qs = TimeReport.objects.filter(year=year, term=term).all() return_value = serializers.serialize('json', qs) else: return_value = 'fail' mimetype = "application/json" return HttpResponse(return_value, mimetype) Obviously, this view returns the foreign key within the created_by field. How can I make sure I pass along the first_name and the last_name of the Person with each TimeReport entry? If I'm not mistaken, I should use annotate but I am struggling with the way it should be put together... -
Django Cors headers added cors-origin-allow-all=True but still gives 403 forbidden error
I am Working on a project where i have installed django cors headers app and done the cors-origin-allow-all=True but it is still giving 403 forbidden error when i am acceing api endpoints from django rest framework.django cors headers issue -
How to create a model that summary from others model, and not save into database but show in admin page?
I have a problem: I need to create a table in admin page that summary data from others model but it's not a actually real model and not be saved into database. How to implement this? -
django template tag in static js files
I want to use template tag and variables in static js files. I'll give you 3 files. no1_ index.html no2_ inc/index.html no3_ index javascript file no1 file is template. html tags in here. and it refers to no2.file to include some scripts. no2.file has some kinds of script includes. and it refers to no3.file to make my own scripts. in no3.file, I want to deal with my template variables from view.py but at no3.file, It can not read template tags and variables. what can I do for this issue? no1_index.html {% load static %} {% load mathfilters %} {% extends 'mobileWeb/base/base.html' %} {% block content %} {% include 'mobileWeb/inc/index/index.html' %} <div id="map" style="width:80%;height:300px; margin:20px auto; border-radius: 10px;"></div> <div style="width:90%; margin:auto"> <!-- this row will wrapping foreach--> {% for mart in marts %} <div class="row"> <div class="col-xs-5" onclick="martClick({{ mart }})"> {% with "/mobileWeb/images/"|add:mart.imageFileNo|add:".png" as path %} <img src="{% static path %}" style="width:120px; height:120px; margin-top:10px;"> <br> <h3>{{ mart.name }}</h3> {% endwith %} </div> <div class="col-xs-7" style="height:200px; overflow:scroll" data-toggle="modal" data-target="#martModal" data-whatever="{{ mart.id }}_{{ mart.name }}"> {% for item in items %} {% if mart.id == item.mart %} <div> <h4 style="color:mediumpurple;">{{ item.name }}</h4> {% if item.discountPrice == 1 or item.discountPrice == 100 %} <h6><span … -
Django REST Framework - Additional field in ModelSerializer
In my ModelSerializer, I want to add required field re_password. I want to use it during creating User model to check if re_password equals password field. class UserSerializer(serializers.ModelSerializer): class Meta: model = User re_password = serializers.CharField(allow_blank=False, write_only=True) fields = ('email','password') def validate_password(self, password): password, re_password = itemgetter('password', 're_password')(self.initial_data) if not password == re_password: raise serializers.ValidationError('Passwords must be the same.') My problem is that when I add re_password to fields I get error: Field name `re_password` is not valid for model `User`. (which is obvious in this case) But if I don't, serializer don't see my additional field. My goal, is to get following error, when there is no re_password field in POST request: "re_password": [ "This field is required." ] I know that I can write code to check it, but maybe there is a way for a serializer to do it? -
How do I connect forms to models in Django?
I've just started learning Django, and I have questions regarding forms and models. So what I'm trying to create, in simplified feature, is a user inputs his/her basic information--phone #, instagram account, facebook account, and so on--then the data is stored in database and show up dynamically to the user. Just like social media. But I'm having confusion with forms and models. What I first did was create forms, like below (forms.py) : from django import forms from django.contrib.auth.models import User class InputUserInfo(forms.Form): phone = forms.CharField(max_length=20) instagram = forms.CharField(max_length=20) facebook = forms.CharField(max_length=20) # and so on. Don't mind about which field to use. then I have my views.py file, written as below: from django.shortcuts import render, redirect from .forms import InputUserInfo def inputuserinfo(response): if response.method == "POST": form = InputUserInfo(response.POST) if form.is_valid: form.save() return redirect('home') else: form = InputUserInfo() return render(response, 'inputuserinfo.html', {'form' : form } then I have my inputuserinfo.html file, like below: {% extends 'base.html' %} {% block content %} <form method="post" action='/inputuserinfo/'> {% csrf_token %} {{form}} <button type='submit'>Done</button> </form> {% endblock%} Now the problem is, I don't know what to do with my models.py. I don't know which code to write in models.py to store the input … -
Writing a Class Based View that Returns a Model instance made by the authenicated_user
I am super new to Python and Django and am trying to get the Model instance made by the current user. I can get the current user.id as the pk but am struggling to find out how to reference that current user and apply that to the View. Currently I have the CustomUser and Profile on a OneToOne Relationship but both are running different pk's ( which makes sense) but while i can get the current users id and apply it through a url its referencing the CustomUser and not the Profile. So i have this View being accessed by a button in a User Inferface that is supposed to call the Profile instance in a DetailView and then a follow on UpdateView class CustomUser(AbstractUser): class Meta: pass def __str__(self): return f"Username: {self.username}, PK: {self.id}" class Profile(models.Model): # TODO: Define fields here # add additional templates under templates/users. Add to the tuples below in this format. USER_TEMPLATES = ( ('users/generic/generic.html', ('generic')), ('users/clothing/clothing.html',('clothing')) ) #model fields author = models.OneToOneField(CustomUser, on_delete=models.CASCADE, editable = False, related_name = 'user') title = models.CharField(verbose_name = 'Company Name', max_length= 50) slug = models.SlugField(editable=False,max_length = settings.SLUG_TITLE_MAX_LENGTH) st_address = models.CharField( max_length=50, verbose_name = 'Street Address') city = models.CharField(blank = … -
Django get_or_create multiple rows without loops
I have an existing Django model which may or may not contain the results from a python calculation. How do I test for and add multiple rows if it does not exist? The docs explain very nicely how to do one entry. Additionally there are various solutions for how to insert multiple rows. I specifically need to (i) add bulk (ii) if it does not already exist. If loops are the only way, then so be it. -
importing top-level Package - python
/folder1 /packageFolder /subfolder /foo.py /folder2 /bar.py Hello I'm trying to import bar.py into foo.py but I'm getting this error: ValueError: attempted relative import beyond top-level package why? and how can I solve this? -
Assigning a rank to the scores from the database in django and displaying it on the html page
I'm creating a quiz app, i am done till displaying scores, but i'm stuck at ranking the students based on their scores which has directly been stored in the database, so how do i get scores from the database and rank the students according to their scores and display it on my html page, I'm using django for this, requesting model, views, and html code. -
Display User's Django Rest Framework Auth token in templates
I recently implemented Django Rest Framework into my project, and I was wondering if it is possible for me to display the Token that has the associated User object attached to it. So if I, for example could do this in the templates: {{ user.token }}. -
FormView: form is absent in the context
Django 3.0.4 template {% debug %} <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Copy"> </form> forms.py from django import forms from yandex_ads.models import YandexTextAdTemplates def get_choices(): return [(item.id, str(item)) for item in YandexTextAdTemplates.objects.all()] class CopyForm(forms.Form): forms.ChoiceField(choices=get_choices()) views.py from django.views.generic.edit import FormView class CopyAdTemplate(FormView): template_name = 'yandex_ads/copy_form.html' form_class = CopyForm success_url = reverse_lazy("home") **The problem: ** form param is not transmitted to the context. It is absent. But in the screenshot (with a black background) it is visible that FormMixin handled the form. Well, it disappeared somewhere. Could you help me solve or at least localize the problem?