Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DjangoCMS - Admin Account Details
I took a break from working on a website I am currently building however I cannot for the life of me remember the admin account details.. I thought I could just create a new superuser however it appears the users for DjangoCMS and Django Admin may be different.. Does anyone know of a way to either reset the password or create a new user explicitly for DjangoCMS? I have attempted python3 manage.py createsuperuser however the user account created doesn't seem to work. Any help would be appreciated! There is very little on google about DjangoCMS.. -
How to update the value of nested dictionary and avoid bidding
When i update the value given specific keys in a nested dictionary, i seem to be binding the dictionnary to the value. This is a problem when i loop through a list of values as only the last value is saved. Instead i would like to only update the value given the relevant keys. In the code below, the last element of the list list will replace the value for all the dates for a given column_header: new_calendar = init_calendar(year,month,column_headers) for element in list: new_calendar[element.date][element.column_headers] = element init_calendar creates a nested dictionary where all dates for a given month have the dictionary {column_header1:None, column_header2: None, ...}. The for loop is meant to overrides the None value with an instance of object Element for a given date and column_header. list is a queryset of elements of class models.Element How could i update the new_calendar so that for a given instance element of the Element object, new_calendar[element.date][element.column_header] is updated with element ? Thank you -
Django filter many to many list of objects that contains all the items of a list
Models.py class Track(models.Model): title = models.CharField(max_length=300,null=True, blank=True) artists = models.ManyToManyField(Artist, related_name='track_related') artist_list = [mila, fuad, habib] I have to filter all the track that's artists contain all the artist from artist_list Mila, Fuad, and Habib I tried Track.objects.filter(artists__in=artist_list).annotate(num_artist=Count('artists')).filter(num_artist=len(artist_list)) But its not woking and also i think my logic isnt fully correct. -
Best practices in loading content into HTML
I am currently working on a project but haven't really done much on the frontend side. I have a relatively small dataset (around 130 rows, 7 field each). I am using Python backend to gather and manipulate the data. My question is how to load it into the HTML table. I have 2 ideas. 1st is to preload the table with data using Django, generate the HTML with all the data and then use JS to sort/filter/any manipulation regarding the content. 2nd one is to load all the data into a DB table, use JS to load it into HTML table. The data always comes from Python, preferably updated every half an hour or so. The JS will take care of the sorting/filtering functions. What is the best practice to load the data into the table? Thanks in advance! -
Committing save operations record by record inside threads in Django
My goal is to make Django save records to DB record by record inside a thread. My code looks like this: class MyThread(threading.Thread): def __init__(self, data, *args, **kwargs): self.data = data super(MyThread, self).__init__(*args, **kwargs) def run(self): for record in data: s = MySerializer(data=record) if s.is_valid(): s.save() # I want this record to appear in db at once I have ATOMIC_REQUESTS set to True inside settings.py. What I have tried to do is to include the s.save() command inside a transation like this: if s.is_valid(): with transaction.atomic: s.save() But it did not help. I wonder whether this is possible and isn't it an anti-pattern ? -
LookupError: No installed app with label "admin"
So I'm trying to run my development server using the command "python manage.py runserver" But whenever I try to run it, it gives me this error; Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 125, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_countries' Traceback (most recent call last): File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'admin' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Kasutaja\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", … -
Google Photos Oauth2 flow returns error 502
I am attempting to use the Google Photos API via my django based web application. During the Oauth flow I am getting error 502 bad gateway. -
Using a foreign key's attribute as a field in a model (Django)
Let's say I have these as a code class Transaction(models.Model): item = models.ForeignKey(Item,on_delete=models.PROTECT) total_transaction = get_price() coupon = models.ForeignKey(Coupon,on_delete=models.PROTECT) def get_price(self): return self.item.price * self.coupon.percentage // 100 I want to use the coupon's percentage and item's price to put in total_transaction, but i don't seem to be able to pass in the function as it says "self" is required? How do I work around this? -
Flask - jinja2 access data from filtered result
data: [ { "name": "fixed", "addr": "172.16.1.100", "active": "Yes" }, { "name": "floating", "addr": "10.90.80.10" "active": "No" } ] i am trying to filter this data in the jinga2 template and value from the filtered result. {{ data|selectattr("name", "equalto", "floating")}} this gives me { "name": "floating", "addr": "10.90.80.10" "active": "No" } i would like to get the active status from this result. i tried {{ data|selectattr("name", "equalto", "floating")|attr("active")}} and it returns as blank. what is the right way to do this? to access the attribute after applying a jinga filter "|" Note: I just tried below and it works. The problem is when i apply filter and then i try to access an attribute. using the attr menthod. This works {{ data[0]['active'] }} This doesnt {{ data|first|attr('active') }} -
Django polls app getting vote count to display
I'm new to Django and have been creating the polls app. I have managed to get everything working except for the results button doesn't show the number of votes it just shows some code: {{ choice.votes }} votes My results template is: {% extends 'base.html' %} {% block content %} <h1 class="mb-5 text-center">{{ question.question_text }}</h1> <ul class="list-group mb-5"> {% for choice in question.choice_set.all %} <li class="list-group-item"> {{ choice.choice_text }} <span class="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span> </li> {% endfor %} </ul> <a class="btn btn-secondary" href="{% url 'polls:index' %}">Back To Polls</a> <a class="btn btn-dark" href="{% url 'polls:detail' question.id %}">Vote again?</a> {% endblock %} My views vote function is: def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) -
Adding multiple fields to SQLite3 in a single Django migration
I have a SQLite3 table with ~2 million rows and ~30 columns. I need to add 4 more fields to the model. I add new fields to models.py, run manage.py makemigrations and then manage.py migrate. When I check SQL queries, Django creates a new table (and drops the old one) for each new field instead of creating a new table once with all 4 fields added. This increases migration time 4 times which results in ~1 hour. Is it possible to optimize this somehow and force Django to add all 4 fields in a single CREATE TABLE statement? -
Unable to connect matplot graph to database in Django
I would be very grateful for any help to my problem: Goal: I am trying to plot a matplot pie chart with data from my sqlite database. I achieved to plot a simple pie chart on my webpage (without using the database). My problem: In order to connect the data from my database, I used the filter() and aggregate() methods. On the webpage the plot is not loading (I only receive an image symbol). What I want to plot: In my plot I want to display the sum of the costs(spendings) in each category as a pie plot. Here is my code: models.py: CHOICES = ( ('rent', 'Rent'), ('grocery', 'Grocery'), ('shopping', 'Shopping'), ('gym', 'Gym'), ('phone', 'Phone'), ('freetime', 'Freetime'), ('other', 'Other') ) class UserDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="new_spending", null=True) expense_name = models.CharField(max_length=255) cost = models.FloatField() date_added = models.DateTimeField() category = models.CharField(max_length=25, choices=CHOICES) notes = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.title views.py: from django.shortcuts import render from django.http import HttpResponse import matplotlib.pyplot as plt from django.db.models import Sum from .models import UserDetails from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure def statistics(request): return render(request, "budget_app/statistics.html") def test_plot(request): fig = Figure() ax = fig.add_subplot(111, aspect='equal') #The problem must lie … -
How to display multiple object data in html table in django template
I passed two queryset objects from views to template both have product data with its features now the main problem is how to show this both objects data simultaneously in HTML table? table structure: features1 | product1 features value 1 | product2 feature value 1 features2 | product1 features value 2 | product2 feature value 2 ... <tbody> {% for a in product_data %}{% for b in product_data_2 %} <tr class="row" style="line-height: 3"> {% if forloop.counter == forloop.parentloop.counter %} {% for feature_data in a.product_features.all %}{% for feature_data_1 in b.product_features.all %} <td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: left; font-weight: bold;"> {{ feature_data.feature.feature_name }} </td> <td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: center;"> {{ feature_data.product_feature_value }} </td> <td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: center;"> {{ feature_data_1.product_feature_value }} </td> {% endfor %}{% endfor %} {% elif forloop.counter < forloop.parentloop.counter %} something {% elif forloop.parentloop.counter < forloop.counter %} something {% endif %} </tr> {% endfor %}{% endfor %} </tbody> please try to answer i tried but nothing work -
Django API throws Exception Value: Object of type ParserError is not JSON serializable
New to development of API. Any help or article would really help. my views.py @api_view(["POST"]) def retrieve_base64_as_pdf(request): try: #base_64_input = request.POST.get('ImageBase64String') body_unicode = request.body.decode('utf-8') print(len(body_unicode)) body = json.loads(body_unicode) print(len(body)) base_64_input = body['ImageBase64String'] doc_ref_id = body['DocRefID'] #base_64_input = json.loads(request.body["ImageBase64String"]) pdf = base64.b64decode(base_64_input) #build PDF with open(os.path.expanduser('life/lpo-test.pdf'), 'wb') as fout: fout.write(pdf) responses = single_page_extractor(file_names='life/lpo-test.pdf',client_doc_ref_id=doc_ref_id) # return Response(responses, safe=False) return Response(responses, status=status.HTTP_200_OK) # responses = json.responses.replace("\'", '') # return Response(responses, status=status.HTTP_200_OK, content_type='json') except ValueError as e: os.remove('life/lpo-test.pdf') return Response(e, status=status.HTTP_400_BAD_REQUEST) my process, 1. consume base 64 run my logic and output json. It works 99% of the time but throws bad request at times. 1. The json input is the same for all inputs. error message: exception: Exception Value: Object of type ParserError is not JSON serializable error: ParserError('Error tokenizing data. C error: Expected 1 fields in line 3, saw 12\n') -
502 Bad Gateway, I messed up users and groups permissions on digitalocean ubuntu for django deployment
I have created a droplet, an ubuntu 18.04 server on digitalocen successfully. Followed the install digitalocean's guide and ran the gunicorn,nginx, django etc. and ran the website successfully on the browser using my ip address i.e. firewalls, gunicorn and nginx and everything were configured correctly. During the testing while uploading the images to the media folder I got an error "permissions denied" (POST error). Found somewhere the below code on google and thought it solves the permissions related problem: https://www.semicolonworld.com/question/55551/django-errno-13-permission-denied-39-var-www-media-animals-user-uploads-39 sudo groupadd varwwwusers sudo adduser www-data varwwwusers sudo chgrp -R varwwwusers /var/www/ sudo chmod -R 760 /var/www/ But the above code messed up everything and ran into "502 Bad Gateway". I am not very familiar with Linux deployments. Can someone help me investigating and resolving this issue. I think I have messed up the users, groups permissions. How can I get this resolved OR how can I revert what I did OR is there any activity logs I can see and investigate. Thanks for the help in advance. -
ModuleNotFoundError in Django after installing the socail-auth-app
ModuleNotFoundError: No module named 'social django The error keeps poping up when I tried to run migrate. I Installed the pip3 install social-auth-app-django and everything was downloaded. AUTHENTICATION_BACKENDS=( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) I have also included the soical django in INSTALLED_APPS. Is there anything wrong in this? -
Get django permissions for logged in user to show/hide menus according to user role
I am new to django and am working on a django project, where I want to show/hide menus in accordance with the permissions a logged in user has. I am using Django Rest Framework and JWT. I did not find any url in rest_auth.urls to fetch all the permissions logged in user has. Can you please help me, how would you go about it ? -
Concat datetime object with string
I have following data and I want to create pymongo query in string format. def epoch_to_date(epoach): return datetime.datetime.fromtimestamp(epoach / 1000) start_date = epoch_to_date(params.get('start_date')) end_date = epoch_to_date(params.get('end_date')) query = "collection.find({'code':"+obj.uuid+", createdDate: { $gte: "+start_date+", $lte: "+end_date+" } },{'_id': False}).sort('createdDate', -1).limit(100)" but I'm not able to convert datetime object in string format it is giving me following error query = "collection.find({'code':"+obj.uuid+", createdDate: { $gte: "+start_date+", $lte: "+end_date+" } },{'_id': False}).sort('createdDate', -1).limit(100)" TypeError: coercing to Unicode: need string or buffer, datetime.datetime found Can you tell me how can I use this datetime object in string format. -
Facebook and Google Authentication process cancelled using Djoser in Django Rest framework with Next.js+React as frontend
I used Djoser to handle basic user authentication functions for me in Django Rest Framework. And I tried to use its social auth endpoint. According to its documentation, if I understand correctly, I first added redirect_uri to its endpoint, e.g. : http://127.0.0.1:8000/auth/o/facebook/?redirect_uri=http://localhost:3000 It worked fine. Then I used the link to authenticate and it returned code and state (as data in the code below) to me as queries in the redirect_uri. But then when I post back the code and state in getInitialProps method from Next.js server to my backend, const authResponse = await axios.post(`http://127.0.0.1:8000/user_info/o/facebook/`,data,{ headers:{ 'Content-Type':'application/x-www-form-urlencoded' } } Django returns a status code 400. Then I used postman to test posting code and state with 'Content-Type':'application/x-www-form-urlencoded', it showed on the window: { "non_field_errors": [ "Authentication process canceled" ] } I tried the same case with Google OAuth2. The following is the python code in my settings.py. import os from dotenv import load_dotenv load_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = ['127.0.0.1','0.0.0.0'] INSTALLED_APPS = [ ... 'djoser', 'social_django', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'user_info', ... ] ... CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", ] ROOT_URLCONF = 'myprojectname.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
Django: how to show all available data inside an array?
In djangorestframework, there is a browsable api. But how do I show all related possible api calls that make only one at a time. question link -
PyZ3950 - EncodingError: Bad type to bytes_write after porting to Python 3
I am trying to connect to a database using PyZ3950 in a django application to retrieve data. This module is very old, and it has been working for Python 2, but I can't find a working version for Python 3. https://github.com/danizen/PyZ3950 repo on github managed to port the application using 2to3.py and some hand changes, but although this library installs just fine, it throws the error PyZ3950.asn1.EncodingError: Bad type to bytes_write when I try the Connection method from zoom. Here is the full Traceback: Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from PyZ3950 import zoom >>> conn = zoom.Connection ('z3950.loc.gov', 7090) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\Downloads\Applications\PyZ3950-danizen\PyZ3950-master\PyZ3950\zoom.py", line 276, in __init__ self.connect() File "D:\Downloads\Applications\PyZ3950-danizen\PyZ3950-master\PyZ3950\zoom.py", line 301, in connect self._cli = z3950.Client (self.host, self.port, File "D:\Downloads\Applications\PyZ3950-danizen\PyZ3950-master\PyZ3950\z3950.py", line 510, in __init__ self.initresp = self.transact ( File "D:\Downloads\Applications\PyZ3950-danizen\PyZ3950-master\PyZ3950\z3950.py", line 529, in transact b = self.encode_ctx.encode (APDU, to_send) File "D:\Downloads\Applications\PyZ3950-danizen\PyZ3950-master\PyZ3950\asn1.py", line 622, in encode spec.encode (self, data) File "D:\Downloads\Applications\PyZ3950-danizen\PyZ3950-master\PyZ3950\asn1.py", line 1192, in encode ctyp.encode (ctx, val) File "D:\Downloads\Applications\PyZ3950-danizen\PyZ3950-master\PyZ3950\asn1.py", line 858, in encode self.typ.encode (ctx, val) File "D:\Downloads\Applications\PyZ3950-danizen\PyZ3950-master\PyZ3950\asn1.py", line 796, in … -
How to use djangorestframworkjwt properly
I'm trying to implement djangorestframworkjwt but I'm facing one problem as showing in image below. I'm trying to follow djangorestframworkjwt documentations and rest-auth documentation. Here I'm using custom user model from .managers import CustomUserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(_("Username"), max_length=50, unique=True) .......... USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] objects = CustomUserManager() def __str__(self): return self.email def get_full_name(self): return self.userprofile.first_name + " " + self.userprofile.last_name def get_short_name(self): return self.userprofile.first_name class UserProfile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) first_name = models.CharField(_("First name"), max_length=50) .................... urls.py urlpatterns = [ url(r'^api-token-auth/', obtain_jwt_token), url(r'^api-token-refresh/', refresh_jwt_token), url(r'^api-token-verify/', verify_jwt_token), path('api/v1/', include('apps.urls.v_1')), ] and settings.py # Application definition TENANT_MODEL = "tenant.Client" SHARED_APPS = [ "tenant_schemas", "apps.tenant" ] TENANT_APPS = [ ......... "rest_framework", 'rest_framework.authtoken', 'rest_auth', "apps.users", ] INSTALLED_APPS = SHARED_APPS + TENANT_APPS REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( # 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } REST_USE_JWT = True Am I doing somethings wrongs. Here I'm using three packages djangorestframeworks, rest-auth, djangorestframworkjwt. I'm using rest-auth and django restframworkjwt -
refreshing Data Div inside Ajax request
I am learning Javascript and I am having one doubt I am trying to create a profile picture .... There is a dropdown... Once it click it having two options 1) Update your Profile Picture 2) If there is any profile picture it will show Delete options otherwise it will hide this options Here is my code <div class="dropdown-menu"> <a class="dropdown-item"><input name="input_file" type="file" id="profile-pic-upload" style="display: none;" /> <label for="profile-pic-upload">Upload Profile Picture</label> </a> {% if user_profile.profile_pic %} <a class="dropdown-item delete" href="javascript:" style="font-size : 14px;">Delete</a> {% endif %} </div> Here is my javascript part for Deleting and updating the picture $(".delete").click(function () { $('.loading').show(); var url = "{% url 'user-profile-image-delete' %}"; $.ajax({ type: 'POST', url: url, data: $("#new_form").serialize(), cache: false, success: function (data, status) { $('#imagePreview').css('background-image', 'url('+'{% static 'assets/img/user-64x.png' %}'+')'); if (data['status'] == "success") { } else { toastr.error(data.msg); } } }); }); $("#profile-pic-upload").change(function () { var input_detail = this; var data = new FormData(); var file = this.files[0]; data.append("file", file); $.ajax({ type: 'POST', data: data, contentType: false, processData: false, url: $("#profile-file-upload").data('action'), cache: false, success: function (data, status) { if (data['status'] == true) { toastr.success(data.msg); var randomId = new Date().getTime(); $('#imagePreview').css('background-image', 'url(' + data.profile_pic + '?random=' + randomId + ')'); } else … -
Django: Lookup User OnetoOne Field using username with Model View Sets (Django Rest API)
My task is for an administrator in my application to be able to create and update an employee's details. Given that django's user model simplifies authentication, I used it as a OnetoOneField in my Employee Model, representing the key as the employee ID (username). My Model - class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True) date_of_join = models.DateField(blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) designation = models.CharField(max_length=255, null=True) mobile = models.CharField(max_length=255, null=True) personal_email = models.CharField(max_length=255, blank=True, null=True) official_email = models.CharField(max_length=255, blank=True, null=True) current_station = models.CharField( max_length=255, default="Chennai", null=True) def __str__(self): return self.name Serializers - class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('user', 'name', 'date_of_join', 'date_of_birth', 'designation', 'mobile', 'landline', 'personal_email', 'official_email', 'current_station') My Model View Set: class EmployeeListSet(viewsets.ModelViewSet): lookup_field = 'user' serializer_class = EmployeeSerializer queryset = Employee.objects.all() Browsable API of a specific Employee filtered by user ID As shown in the image, the user field shows me pk instead of user.username. I am able to see the username in the HTML Form for POST in the browsable API, however the json does not return the username by default and rather returns pk. I want to be able to lookup and update an employee's details based on the username … -
Django pop up modal after Inserting/updating data
I've been searching in google and SO about pop up message when user submit but that doesnt work when i apply it to my code, I just want that if the user update/insert data, a pop up modal message appears I have this form in my html <form method="post" id="myform" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table id="blacklistgrids" border="2px"> <tr> {% for v in table.0 %} {% if forloop.first %} <th id="thupdate">{{v}}</th> {% else %} <th ><input type="text" name="updatedate" value="{{ v }}"></th> {% endif %} {% endfor %} <th hidden></th> <th data-id='headerss' id='headerave'>Average</th> </tr> <tbody> {% for row in table|slice:"1:" %} <tr class="tr2update"> <td><input type="text" value="{{row.0}}" name="students" hidden>{% for n in teacherStudents %}{{n.Students_Enrollment_Records.Student_Users}}{% endfor %}</td> <td class="tdupdate" hidden><input type="text" hidden></td> {% for teacher in students %} <input type="hidden" name="id" value="{{teacher.id}}"/> <td> <input type="text" data-form-field="{{teacher.id}}" name="oldgrad" class="oldgrad" value="{{teacher.Grade|floatformat:'2'}}"/> </td> {% endfor %} {% for avg in average %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" value="{{average.average_grade|floatformat:'2'}}" readonly/></td> {% endfor %} </tr> {% endfor %} </tbody> </table> <div class="buttons"> <input type="submit" value="&nearrow;&nbsp;Update" class="save" formaction="/updategrades/"> </div> </form> <script> if (typeof jqXhr.success != 'undefined') { $('#thanksModal').modal('show'); } else { $('#myform').html(jqXhr); } </script> and this is my views.py import json def updategrades(request): /some logic/ return …