Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, saving image, OSError: cannot identify image file
CODE: if request.is_ajax(): testpic = TestPic.objects.get(pk=1) form = TestPicForm(request.POST, request.FILES) if form.is_valid(): from PIL import Image from io import BytesIO data = request.FILES['file'] data_50 = request.FILES['file'] input_file = BytesIO(data.read()) image_crop = Image.open(input_file) print('print 2') # Problem starts. input_file_50 = BytesIO(data_50.read()) image_crop_50 = Image.open(input_file_50) image_crop = image_crop.crop((1,1,100,100)) image_crop_50 = image_crop_50.crop((40, 40, 140, 140)) image_resize = image_crop.resize((300, 300), Image.ANTIALIAS) image_resize_50 = image_crop_50.resize((50, 50), Image.ANTIALIAS) image_file = BytesIO() image_resize.save(image_file, 'JPEG') image_file_50 = BytesIO() image_resize_50.save(image_file_50, 'JPEG') data.file = image_file testpic.file = data data_50.file = image_file_50 testpic.file_50 = data_50 testpic.save() return JsonResponse({'success': 'file_uploaded'}) return JsonResponse({'success': 'failed'}) And Traceback is like this: print 2 Traceback (most recent call last): ... I remove some lines ... File "D:\pythonDev\project\upward\chatkaboo\authapp\views.py", line 844, in crop image_crop_50 = Image.open(input_file_50) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\PIL\Image.py", line 2590, in open % (filename if filename else fp)) OSError: cannot identify image file <_io.BytesIO object at 0x0000024B40510BF8> Description: As you can see on above my code's purpose is that saving requested image file. I tried to find what happened and which line has problem. So print 2 was printed, and therefore input_file_50 = BytesIO(data_50.read()) line has problem. Question: Why this error happened? BytesIO can only deal with just one file at a time? How can I deal with … -
I want to get specific post by type slug
hey i am trying to get specific post by typing slug of the post but i am getting error 'Post' object is not iterable Can u help me with that here is my codes : url.py : urlpatterns = [ url(r'^$',views.list_of_post, name = 'list_of_post'), url(r'^(?P<slug>[-\w]+)/$' ,views.post_detail , name = 'post_detail'), ] here is my view.py : def post_detail(request, slug): # post = get_object_or_404(Post, slug=slug) # template = 'music/post_detail.html' # context = {'post':post} # return render(request , template , context) try: post = Post.objects.get(slug = slug) except Post.DoesNotExist: raise Http404('Post Doesnot Exist') return render(request,'music/post_detail.html',{'post':post}) and here is my model.py for post - slug def get_absolute_url(self): return reverse('music:post_detail', args=[self.slug]) btw i have clickable titles for posts and also i am getting error 404 not found page i think problem is somewhere in URL -
how to set domain name for bandwagong host
I am trying to deploy my Django project on my new-purchased bandwagong VPS server, to be clarified, I am total a layman to server/network, but I just tried based on my intuition. Everything works smoothly except setting the domain name, I have been bought one domain from resellerclub, however, I have no idea how to combine my domain name and server, I noticed on the control page it has two keywords host name and DNS in this picture exactly, since these two keywords information are provided by my domain manager. Naturally, I fill the blank, but when I started the server with 0.0.0.0:80, and visit new domain name bravopan.com, it does not appear my project homepage, so I want to ask some network experts how to integrate my domain name and bandwagong server? -
heroku not sending email
I have an app in heroku writen in django. my app just sends email to one user when ask for password reset or even account activation which is the email I used in creating the heroku app. all other users are just kept waiting ti receive an email because there is no error but emails are never delivered I was using sebdgrid and it was doing the same now am using mailgun but still the single email only receivea emails from the app -
Change boolean value with form submit button (Django)
I have this table with products where one of the cells is a submit button "add to cart". I would like to change the boolean value to true so it appears in /cart. this is my table: <table> <tr> <th>List of car parts available:</th> </tr> <tr> <th>Name</th> <th>Price</th> </tr> {% for product in products_list %} <tr> <td>{{ product.name }}</td> <td>${{ product.price }}</td> <td>{% if not product.in_cart %} <form action="{% url 'cart' %}" method="post"> {% csrf_token %} <input type="submit" value="Add to cart"> </form> {% else %} {{ print }} {% endif %} </td> </tr> {% endfor %} </table> <a href="{% url 'cart' %}">See cart</a> I was hoping to use the post method of the submit button to change the boolean value like the following: def index(request): products_list = Product.objects.all() template = loader.get_template('products/index.html') context = {'products_list': products_list} return HttpResponse(template.render(context, request)) if request.method == 'POST': product.in_cart = True Any ideas? Thanks! -
Django test case failing
I am pretty new to Django and I ran into a problem. I am not even sure if its a stupid question or not. I want to test if my home view contains link to my topics view but despite everything being at place the test is getting failed. Any help appreciated .It shows the following error Traceback (most recent call last): File "/home/abc/Desktop/python-environments/second/tutorial/myproject/boards/tests.py", line 26, in test_home_view_contains_link_to_topics_page self.assertContains(self.response, 'href="{0}"'.format(board_topics_url)) File "/home/abc/Desktop/python-environments/second/lib/python3.5/site-packages/django/test/testcases.py", line 369, in assertContains self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr) AssertionError: False is not true : Couldn't find 'href="/boards/1/"' in response here are my files urls.py from django.urls import path from . import views app_name = 'boards' urlpatterns = [ path('', views.home, name='home'), path('<int:d>/', views.topics, name='topics'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Board, topic def home(request): boards = Board.objects.all() return render(request, 'boards/index.html', {'boards': boards}) def topics(request, d): board = get_object_or_404(Board, id=d) return render(request, 'boards/topics.html', {'boards': board}) index.html {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Boards</title> <link rel="stylesheet" href="{% static 'boards/css/bootstrap.min.css' %}"> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> <li class="breadcrumb-item active">Boards</li> </ol> <table class="table"> <thead class="thead-inverse"> <tr> <th>Board</th> <th>Posts</th> <th>Topics</th> <th>Last Post</th> </tr> </thead> <tbody> {% … -
Accessing template in testing - Django
At the moment I am struggling to access a specific quiz in the testing part of my app. It is saying that there is a 404 when I print it out but the template does exist. Below are my tests, urls and method that allows the user to take the quiz. I can add the models if need. Tests class TestQuiz(TestCase): @classmethod def setUpTestData(cls): user1 = User.objects.create_user(username="test1", password="test1", is_quizmaster=True) user2 = User.objects.create_user(username="test2", password="test2", is_player=True) sport = Subject.objects.create(name='Sport', color='#CCCCCC') sport.save() quiz = Quiz.objects.create(owner=user1, name='quiz', subject=sport) quiz.save() def test_player_get_test(self): self.client.login(username='test1', password='test1') quiz = Quiz.objects.get(name='quiz') response = self.client.get('/quiz/%d/' % quiz.id) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'users/players/player_tournament_form.html') URls path('players/', include(([ path('', player_view.PracticeQuizListView.as_view(), path('interests/', player_view.PlayerInterestsView.as_view(), name='player_interests'), path('taken/', player_view.TakenPracticeQuizListView.as_view(), name='player_taken_quiz'), path('taken-tournament/', player_view.TakenTournamentListView.as_view(), name='player_taken_tournament'), path('quiz/<int:pk>/', player_view.take_quiz, name='player_take_quiz'), path('tournament/<int:pk>/', player_view.take_tournament, ], 'users'), namespace='players')), Method @login_required @player_required # Custom wrapper def take_quiz(request, pk): # Raising Http404 instead of the model’s DoesNotExist exception quiz = get_object_or_404(Quiz, pk=pk) # Requesting the user player player = request.user.player # Getting the total question count of the quiz total_questions = quiz.questions.count() # Getting all unanswered questions and count unanswered_questions = player.get_unanswered_questions(quiz) total_unanswered_questions = unanswered_questions.count() # Getting the progress of the quiz. This will increment based off the question count progress = 100 - round(((total_unanswered_questions - 1) … -
How do I customize Django Select2 fields?
I started using django-select2 with my forms in one of my apps and I am looking for how to customize the form fields. For example, with one of the form fields you can select a country, so an icon next to the name of the country would be nice. Also, maybe present the countries in groups like Popular or by continent. The Select2 site has some examples that I would like to replicate. On django-select2 documentation is not clear on how to do something like that. Have you ever tried something like this ? -
Change boolean value on user click Django
I have this table with products with the following columns: Name, price and add to cart if the product is not in cart. <table> <tr> <th>List of car parts available:</th> </tr> <tr> <th>Name</th> <th>Price</th> </tr> {% for product in products_list %} <tr> <td>{{ product.name }}</td> <td>${{ product.price }}</td> <td>{% if not product.in_cart %} <a href="cart/">Add to cart</a> {{ product.in_cart = True }} {% else %} {{ print }} {% endif %} </td> </tr> {% endfor %} </table> <a href="cart/">See cart</a> And these are my views: def index(request): products_list = Product.objects.all() template = loader.get_template('products/index.html') context = {'products_list': products_list} return HttpResponse(template.render(context, request)) def cart(request): cart_list = Product.objects.filter(in_cart = True) template_cart = loader.get_template('cart/cart.html') context = {'cart_list': cart_list} return HttpResponse(template_cart.render(context, request)) Once the user clicks on add to cart, I would like to change the product's in_cart value to True so it appears in /cart. Same for remove from cart in the cart template. How can I do that? Thanks :) -
How to import a class from another file which is importing first class for
Hello I want to import a class from another class my file structure is something like this. folder1/ file1.py folder2/ file2.py file1.py from folder2.file2 import B class A: some thing file2.py from folder1.file1 import A class B: something # class C(A): something When I run file1. It says File "./folder1/file1.py", line 1, in <module> from folder2.file2 import B File "./folder2/models.py", line 1, in <module> from folder1.models import A ImportError: cannot import name 'A' Thanks In Advance. -
error: failed to push some refs to 'https://git.heroku.com/xxxxxxxxx.git'
I got an error,error: failed to push some refs to 'https://git.heroku.com/xxxxxxxxx.git'.I want to upload my application which be made Django to heroku.I run heroku create xxxxxxxxx. Counting objects: 6951, done. Delta compression using up to 4 threads. Compressing objects: 100% (5952/5952), done. Writing objects: 100% (6951/6951), 11.21 MiB | 891.00 KiB/s, done. Total 6951 (delta 2087), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.5 (you are using python-3.6.4, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.5). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.6.4 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: Collecting alabaster==0.7.10 (from -r /tmp/build_6adefb27873345001cb4512d3fd963e3/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/2e/c3/9b7dcd8548cf2c00531763ba154e524af575e8f36701bacfe5bcadc67440/alabaster-0.7.10-py2.py3-none-any.whl remote: Collecting anaconda-client==1.6.9 (from -r /tmp/build_6adefb27873345001cb4512d3fd963e3/requirements.txt (line 2)) remote: Could not find a version that satisfies the requirement anaconda-client==1.6.9 (from -r /tmp/build_6adefb27873345001cb4512d3fd963e3/requirements.txt (line 2)) (from versions: 1.1.1, 1.2.2) remote: No matching distribution found for anaconda-client==1.6.9 (from -r /tmp/build_6adefb27873345001cb4512d3fd963e3/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to xxxxxxxxx. remote: To https://git.heroku.com/xxxxxxxxx.git ! [remote … -
Why am I getting "No application configured for scope type 'web socket'" still?
I am following , django channels 2 chat app tutorial I have at the part "writing your first consumer", I exactly did what is in tutorial, you can find my code here But , I am still unable to connect to my web socket! my error trace : HTTP GET /chat/ji/ 200 [0.05, 127.0.0.1:51247] 2018-06-23 07:51:43,181 - ERROR - ws_protocol - [Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket' /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/internet/defer.py:500:errback /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/internet/defer.py:567:_startRunCallbacks /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/internet/defer.py:653:_runCallbacks /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/internet/defer.py:1442:gotResult --- <exception caught here> --- /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/internet/defer.py:1384:_inlineCallbacks /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/python/failure.py:422:throwExceptionIntoGenerator /anaconda3/envs/chatapp/lib/python3.6/site-packages/daphne/server.py:186:create_application /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/python/threadpool.py:250:inContext /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/python/threadpool.py:266:<lambda> /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/python/context.py:122:callWithContext /anaconda3/envs/chatapp/lib/python3.6/site-packages/twisted/python/context.py:85:callWithContext /anaconda3/envs/chatapp/lib/python3.6/site-packages/channels/staticfiles.py:41:__call__ /anaconda3/envs/chatapp/lib/python3.6/site-packages/channels/routing.py:58:__call__ ] Not Found: /favicon.ico [2018/06/23 07:51:43] HTTP GET /favicon.ico 404 [0.03, 127.0.0.1:51249] [2018/06/23 07:51:47] WebSocket DISCONNECT /ws/chat/ji/ [127.0.0.1:51248] I am unable to get where it's going wrong! -
Set form input as variable in get_queryset
AIM I wish to render results.html with all the locations associated with the search_text entered by the User. To do so, I am attempting to filter the results in get_quersey(), but am struggling to set the form_input variable. I am currently using form_input = self.request.GET.get('search_text'). CODE models.py import re from django.db import models from twython import Twython class Location(models.Model): """ Model representing a Location (which is attached to Hashtag objects through a M2M relationship) """ name = models.CharField(max_length=1400) def __str__(self): return self.name class Hashtag(models.Model): """ Model representing a specific Hashtag serch by user """ search_text = models.CharField(max_length=140, primary_key=True) locations = models.ManyToManyField(Location, blank=True) def __str__(self): """ String for representing the Model object (search_text) """ return self.search_text def display_locations(self): """ Creates a list of the locations attached to the Hashtag model """ return list(self.locations.values_list('name', flat=True).all()) forms.py from django import forms from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from .models import Location, Hashtag class SearchHashtagForm(ModelForm): ''' ModelForm for user to search by hashtag ''' def clean_hashtag(self): data = self.cleaned_data['search_text'] # Check search_query doesn't include '#'. If so, remove it. if data[0] == '#': data = data[1:] return data class Meta: model = Hashtag fields = ['search_text',] labels = {'search_text':_('Hashtag Search'), … -
Not able to catch invalid date 31st - feb in DRF
Not able to catch the exception with invalid date like 31st Feb. It is not even coming in validate method. This field is in nested model serializer. [{'dob': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].'], -
Object of type 'Menu' is not JSON serializable
I made simple api with Django Rest framework. [models.py] from django.db import models class Menu(models.Model): place = models.CharField(max_length=20, primary_key=True) mon = models.CharField(max_length=3000) tue = models.CharField(max_length=3000) wed = models.CharField(max_length=3000) thu = models.CharField(max_length=3000) fri = models.CharField(max_length=3000) sat = models.CharField(max_length=3000) sun = models.CharField(max_length=3000) [serializers.py] from rest_framework import serializers from . import models class MenuSerializer(serializers.ModelSerializer): class Meta: model = models.Menu fields = '__all__' [urls.py] from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ path('', views.Menu.as_view(), name='menu') ] [views.py] from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . import models class Menu(APIView): def get(self, request, format=None): all_menu = models.Menu.objects.all() return Response(status=status.HTTP_200_OK, data=all_menu) When I connect to /menu, It throws TypeError at /menu/ Object of type 'Menu' is not JSON serializable How can I solve this issue? -
How to know what context data returned by any GCBV in django?
Is there any way to know the dictionary returned by any GCBV other than looking at the code. -
django-allauth; How can I limit gmail to an email which has a specific domain?
I'm creating google auth system using django-allauth. I want to limit gmail to a gmail which has a specific domain like school email addrress. How can I do it? -
Django-allauth; How can I skip default Singup form page?
I'm new to Django and I'm creating auth system using django-allauth. What I want to do is just to redirect to home page when a user is logged in or logged out regardress of whether it's first time to log in or not. I set LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL home page. And this problem is almost solved. But the weird thing is when I try to log in using the gmail which has the same email address as the superuser has, it redirects to default sign up page. Seems like it redirects to sign up page if there's conflict between email address. I want to avoid using default template page. Also I want to create a page for conflicting email on my own. Please tell me the best way to avoid using the default template pages. Anyone who can give me tips? -
How do I access Django environment variables using `pipenv`?
There are so many ways to add necessary secrets such as SECRET_KEY as environment variables for Django. I'm wondering what really good ways there might be using pipenv? I've been using .env, is this a professional enough way of doing it? -
Change the default dashes in Django Createview from
Is there a way to change the default dashes in Django CreateView based form to a needed text, e.g. 'Select a Product' in my case? Code of my view form picture -
foreign key called in another serializer
I was looking at the serialzier part in django rest framework. I saw the following models in an example class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() Here you see album is the foreign key in Track model and when we are serializing we are using this foreign key in Album Serializer. class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') Can anyone explain me the difference in calling the album foreign key in Tracks because it is used there versus the album foreign key used in Album? -
HTTP 500 error - Target WSGI script cannot be loaded as Python module
I got the above error while using bitnami django. All settings done according doc: https://docs.bitnami.com/virtual-machine/components/django/#production python version: Python 3.6.4 :: Anaconda, Inc. django version: 2.0.2-3 wsgi.py: import os,sys sys.path.append('/Applications/djangostack-2.0.2-3/apps/django/django_projects/MyProject') os.environ.setdefault("PYTHON_EGG_CACHE", "/Applications/djangostack-2.0.2-3/apps/django/django_projects/MyProject/egg_cache") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyProject.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() httpd-app.conf: <IfDefine !IS_DJANGOSTACK_LOADED> Define IS_DJANGOSTACK_LOADED WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP} </IfDefine> <Directory "/Applications/djangostack-2.0.2-3/apps/django/django_projects/MyProject/MyProject"> Options +MultiViews AllowOverride All <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> WSGIProcessGroup wsgi-djangostack WSGIApplicationGroup %{GLOBAL} Require all granted </Directory> Alias /MyProject/static "/Applications/djangostack-2.0.2-3/apps/django/lib/python3.6/site-packages/Django-2.0.2-py3.6.egg/django/contrib/admin/static" WSGIScriptAlias /MyProject '/Applications/djangostack-2.0.2-3/apps/django/django_projects/MyProject/MyProject/wsgi.py' httpd-prefix.conf: # Include file Include "/Applications/djangostack-2.0.2-3/apps/django/django_projects/MyProject/conf/httpd-app.conf" corresponding url added to /Applications/djangostack-2.0.2-3/apache2/conf/bitnami/bitnami-apps-prefix.conf file But when I'm trying to access app via browser I've got error in log: [Fri Jun 22 16:37:20.873873 2018] [wsgi:error] [pid 29099] [remote ::1:62098] mod_wsgi (pid=29099): Target WSGI script '/Applications/djangostack-2.0.2-3/apps/django/django_projects/MyProject/MyProject/wsgi.py' cannot be loaded as Python module. [Fri Jun 22 16:37:20.874027 2018] [wsgi:error] [pid 29099] [remote ::1:62098] mod_wsgi (pid=29099): Exception occurred processing WSGI script '/Applications/djangostack-2.0.2-3/apps/django/django_projects/MyProject/MyProject/wsgi.py'. [Fri Jun 22 16:37:20.875482 2018] [wsgi:error] [pid 29099] [remote ::1:62098] Traceback (most recent call last): [Fri Jun 22 16:37:20.875554 2018] [wsgi:error] [pid 29099] [remote ::1:62098] File "/Applications/djangostack-2.0.2-3/apps/django/django_projects/MyProject/MyProject/wsgi.py", line 17, in <module> [Fri Jun 22 16:37:20.875568 2018] [wsgi:error] [pid 29099] [remote ::1:62098] application = get_wsgi_application() [Fri Jun … -
Django pass value from view to non-model form
When I call my form within my view, I am trying to pass MY_VALUE to the form as an argument. I am doing this because I want to get my validation out of my views and into my forms. views.py OTHER_VALUE = "the query that i run" if request.method=='POST': form = MY_FORM(request.POST, OTHER_VALUE) forms.py class MY_FORM(forms.Form): real_value = forms.CharField() def clean_real_value(self): if OTHER_VALUE ... This expectedly throws the error: __init__() got an unexpected keyword argument 'OTHER_VALUE' ========= I've tried setting the init with a few different variations of __init__: class MY_FORM(forms.Form): real_value = forms.CharField() def __init__(self, *args, **kwargs): OTHER_VALUE = kwargs.pop('OTHER_VALUE') super(MY_FORM, self).__init__(*args, **kwargs) But I keep getting this type of error: Exception Value: 'employee' Exception Location: /Users/macbook/Desktop/OrgDB/orgchart/forms.py in __init__, line 42 -
How to make a dashboard page functional
I want to have a page working as a dashboard which will have some links, one to a form and another link pointing to a list, all these links being loaded in place (without refreshing the entire page). The problem I'm facing is that after submitting the form, I just get a white page and all the data is lost. I have my views: from django.utils.decorators import method_decorator from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView, ListView @method_decorator(user_passes_test(master_user, login_url = '/'), name='dispatch') class CustomerRegistrationView(LoginRequiredMixin, CreateView): form_class = CustomerRegistrationForm success_url = '/customers-dashboard/' template_name = 'projectcontrol/customers/customer_form.html' class CustomerListView(LoginRequiredMixin, ListView): queryset = CustomerModel.objects.all() template_name = 'projectcontrol/customers/customer_list.html' login_url = '/login/' Next are the urls for the views above app_name = 'projectcontrol' urlpatterns = [ path('customers-dashboard/', TemplateView.as_view(template_name='projectcontrol/customers_dashboard.html'), name='customers-dashboard'), path('customer-form/', CustomerRegistrationView.as_view(), name='customer-form'), path('customer-list/', CustomerListView.as_view(), name='customer-list'), ] My templates for the urls above are divided in three which is customer_form.html, customer_list.html and customers_dashboard.html which this last one is wished to hold the first two urls. How can I make a page similar to a dashboard? Thanks in advance. PS. I think my question will need more information, if it really does, please, let me know and I'll add more information. -
How make 'add members' functionality Django
I am doing a management tool web application. I would like user can click 'add members' button, and the member will be added under 'Members'. I am using ajax to retrieve data from database, but I do not know how to display 'username'. It only displays 'id'. Moreover, I would like added members to stay in page whenever user refreshes the page. project_index.html <form action="" method="GET" id="selection-form"> {% csrf_token %} <select id="member_list"> {% for user in user %} <option value="{{user.pk }} }}"> {{ user.username }} </option> {% endfor %} </select> <input type="button" value="Add member" id="selection-button"> </form> <div id="res"> </div> views.py def member_select(request): selection = request.GET.get('id',None) if selection: data = serializers.serialize('json',User.objects.filter(pk=selection)) else: data = {} return HttpResponse(data, content_type='application/json')