Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
viewing all emails with javasript in django
Im trying to show all objects from Emails model on page. Im trying to make it by creating new elements. I would like the solution to be using javascript. I cant find what the problem may be.I tried inspecting the code, and the elements created with javascript were not there. And yes, there are objects in my Emails module. views.py: import json from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.db import IntegrityError from django.http import JsonResponse from django.shortcuts import HttpResponse, HttpResponseRedirect, render from django.urls import reverse from django.views.decorators.csrf import csrf_exempt from .models import User, Email def index(request): # Authenticated users view their inbox if request.user.is_authenticated: return render(request, "mail/inbox.html") # Everyone else is prompted to sign in else: return HttpResponseRedirect(reverse("login")) @csrf_exempt @login_required def compose(request): # Composing a new email must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # Check recipient emails data = json.loads(request.body) emails = [email.strip() for email in data.get("recipients").split(",")] if emails == [""]: return JsonResponse({ "error": "At least one recipient required." }, status=400) # Convert email addresses to users recipients = [] for email in emails: try: user = User.objects.get(email=email) recipients.append(user) except User.DoesNotExist: return JsonResponse({ "error": f"User with email … -
I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf
views.py def resume(request,id): user_profile=Profile.objects.get(pk=id) template= loader.get_template("Resume/profile.html") html= template.render({'user_profile':user_profile}) options={ 'page-size':'Letter', 'encoding' : 'UTF-8', } pdf= pdfkit.from_string(html,False,options) response= HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition']= 'attachment' return response profile.html {% extends "Resume/layout.html" %} {% block body %} <h2>{{ user_profile.full_name }}</h2> <h2>{{ user_profile.job_title }}</h2> <hr> <h2>{{ user_profile.email }}</h2> <h2>{{ user_profile.phone }}</h2> <h2>{{ user_profile.home_adress }}</h2> <hr> <p>Summary</p> <p> {{ user_profile.work_experience }}</p> <p> {{ user_profile.skills }}</p> <hr> <p>Education</p> <ul> <li> {{user_profile.diplomes}} </li> </ul> <hr> {% endblock %} ![this is th pdf i get ][1] [1]:( https://i.stack.imgur.com/PXlt3.png) I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf can anyone help me with this, i don't know what the problem is -
Add a class field in Django <UL>
<ul> {% topic_menu_full federation "Federation" %} {% topic_menu_full our-school "Our School" %} {% topic_menu_full learning "Learning" %} {% topic_menu_full children "Children" %} {% topic_menu_full parents "Parents" %} </ul> I want to add class to only the last one in the list, for example .red the last one. -
In production mode, react helmet async is not working and How react helmet async works?
Recently, I started playing with meta tags in react. After some research, I found that react-helmet-async is the best library to set meta tags for each page. however, I wanted to want set meta tags for few pages conditionally. I setup metatags for two pages differently, take a look... index.js ReactDOM.render( <React.StrictMode> <HelmetProvider> <App/> </HelmetProvider> </React.StrictMode>, document.getElementById('root') ); pageOne.jsx componentDidMount(){ axios.get('/getTrack/',{params: {id: this.props.match.params.id}}) .then((res) => this.setState({trackData: res.data, isLoading: false})) .catch((err) => console.log(err)) } render() { return ( this.state.isLoading? <div className="page-loader"> <Helmet> {/* Page sittings */} <meta charset="utf-8" /> <meta name="theme-color" content="#000000" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {/* Primary Meta Tags */} <title>Loading...</title> </Helmet> </div> : <div className="main-page"> <Helmet> {/* Page sittings */} <meta charset="utf-8" /> <meta name="theme-color" content="#000000" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {/* Primary Meta Tags */} <title>{this.state.trackData.title}</title> <meta name="title" content={this.state.trackData.title}/> <meta name="description" content={this.state.trackData.desc}/> {/* Open Graph / Facebook */} <meta property="og:type" content="website"/> <meta property="og:url" content="https://example.com/"/> <meta property="og:title" content={this.state.trackData.title}/> <meta property="og:description" content={this.state.trackData.desc}/> <meta property="og:image" content="/logo192.png"/> {/* Twitter */} <meta property="twitter:card" content="summary_large_image"/> <meta property="twitter:url" content="https://example.com/"/> <meta property="twitter:title" content={this.state.trackData.title}/> <meta property="twitter:description" content={this.state.trackData.desc}/> <meta property="twitter:image" content="/logo192.png"/> </Helmet> </div> ) } pageTwo.jsx <Helmet> {/* Primary Meta Tags */} <title>XYZ</title> <meta charset="utf-8" /> <meta name="title" content="xyz"/> <meta name="theme-color" content="#000000" /> <meta name="viewport" … -
Expression contains mixed types: DecimalField, IntegerField. You must set output_field
I am trying execute a query with multiple annotates and i keep getting the output_field required error where as i am already writing that. I have tried to change the output to decimal but does not work. Any idea? My targeted code count = ShareAllocation.objects.filter(session_key=self.storage.request.session.session_key). \ values('share_type__id', 'share_type__code', 'share_type__type'). \ annotate(share_count=Sum('share_type__id')). \ annotate(total_shares=Sum('number_of_shares')). \ annotate(total_paid=ExpressionWrapper(F('amount_paid') * F('total_shares'), output_field=models.IntegerField)).\ annotate(total_unpaid=ExpressionWrapper( F('amount_unpaid') * F('total_shares'), output_field=models.IntegerField ) ).\ count() if count == 0: return False else: return True -
I want to send back a list and a dictionary in django for my site in php
I want to send back a list and a dictionary in django for my site in php,I have a python script that flips a list and an dictionary exemple: list=[ [name,ip,country][name2,ip2,country2] ] dictionary={"name":"A","name2":"B"} I want to put them in jango format and use them in my php code. thanks you!! -
Filtering of user related data in Django / DRF
I am working on a Django application with the Django Rest Framework. I try to do things the Django/DRF way. It is already a non-trivial service, so I have extracted the relevant details from the code to show here. I have the following apps: Report Cluster User The User model, serializer, and view can be considered to be standard for this question. Report class Report(models.Model): slug = models.CharField(unique=True, max_length=100, blank=False, null=False) name = models.CharField(max_length=100, blank=False) clusters = models.ManyToManyField(Cluster, blank=True, related_name='report_clusters') users = models.ManyToManyField(User, blank=True, related_name='report_users') class ReportSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Report fields = ("slug", "url", "name", "clusters") read_only_fields = ('slug', 'clusters') lookup_field = "slug" extra_kwargs = { 'url': {'lookup_field': 'slug'}, 'clusters': {'lookup_field': 'slug'}, } class ReportViewSet(viewsets.ModelViewSet, LoginRequiredMixin): queryset = Report.objects.all() serializer_class = ReportSerializer permission_classes = (permissions.IsAuthenticated, IsAdminUserOrReadOnly) lookup_field = "slug" def get_queryset(self): """Only show user related items.""" return Report.objects.filter(users__id=self.request.user.id) Cluster class Cluster(models.Model): slug = models.CharField(unique=True, max_length=100, blank=False, null=False) name = models.CharField(max_length=100, blank=False, unique=True) users = models.ManyToManyField(User, blank=True) observers = models.ManyToManyField(User, blank=True, related_name='cluster_observer') class ClusterTreeSerializer(serializers.HyperlinkedModelSerializer): # children = serializers.SerializerMethodField() class Meta: model = Cluster fields = ('url', 'slug', 'name') read_only_fields = ('url', 'slug') lookup_field = "slug" extra_kwargs = {'url': {'lookup_field': 'slug'}} class ClusterViewSet(viewsets.ModelViewSet, LoginRequiredMixin): queryset = Cluster.objects.all() serializer_class = ClusterTreeSerializer … -
Could not translate host name “postgres” to address
i a working with django, docker and postgree as db , when i try to compile my project with: docker-compose up --build, i got this error "Could not translate host name “postgres” to address". Please Need help ? -
Favicon not loading in Django
I can't seem to get my favicon to load at all, I have the image in my static folder, all other images load fine on both local and production environments, and I can load the favicon as an image no problem. It just doesn't load as the actual favicon. I have the code to load favicon in the head tag (and all other static files that are loaded there are working, such as style sheets and meta tags). I have {% load static %} at the top of the page as well. Here is my code in the tag which attempts to set the favicon: <link rel="icon" type="image/png" href="{% static 'stockdeepdive/images/favicon.ico' %}"> <link rel="icon" type="image/png" sizes="192x192" href="{% static 'stockdeepdive/images/android-icon-192x192.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'stockdeepdive/images/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="96x96" href="{% static 'stockdeepdive/images/favicon-96x96.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'stockdeepdive/images/favicon-16x16.png' %}"> The images are all located within static folder, then stockdeepdive folder, then finally images folder. All other images are working good. Im not getting any errors in console, but I'm also not seeing any "GET" request for the favicons. Any help greatly appreciated, I've spent hours trying to figure this out. -
What are the dependencies for django-allauth python:3.8.3-alpine Dockerfile
I have a Dockerfile, docker-compose.yml, requirements.txt defined below for a django project. The Dockerfile uses python:3.8.3-alpine and the docker-compose.yml have a db service that uses postgres:12.0-alpine image. I made sure that the dependencies are defined in the Dockerfile as required. However, it seems to me that django-allauth require extra dependencies. I have tried for days to fix this issue but get an error that says This package requires Rust >=1.41.0. ERROR: Failed building wheel for cryptography. I haved pasted the whole error for reference sake. Any help will be much appreciated. Thanks in advance. #requirements.txt Django>=3.1.5,<3.2.0 gunicorn>=20.0.4,<20.1.0 psycopg2-binary>=2.8,<2.9 Pillow>=8.1.0,<8.2.0 django-allauth>=0.44.0,<1.0.0 #Dockerfile # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev \ && apk add libffi-dev libressl-dev \ && apk add --no-cache jpeg-dev zlib-dev libjpeg # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] #docker-compose.yml version: '3.7' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - … -
Embed matplotlib bar graph in html page
I am trying to embed a matplotlib bar graph in html page. I have tried almost everything. here's my code- views.py- def result(request) plt.bar(x,h) plt.xlabel("Personality") plt.ylabel("course") plt.show() return render(request,'result.html') -
Django doesn't read JWT token
My django backend use JWT token for user auth. I store recieved token in 'Authtorization' header using axios. Everything works well. But I noticed problem when I open any link in new tab (ctrl+click), after this I get on to auth page but I still have the token in my header. Why does it happen? -
Empty space below navbar in header
I'm creating a web app using Python - Django. I'm currently working on the front-end part and below my navbar in the header section is a ton of free white-space that I can't seem to get rid off. Also I want my background image behind the whole page, can't seem to get my head around how to do that. It's always either above the body or below it. Any clues? My html with bootstrap: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <link rel="stylesheet" type="text/css" href="{% static 'styles/stylesheet.css' %}"> <link rel="icon" href="{% static 'images/favicon.ico' %}"> <title> Milk - {% block title_block %}Milk Students{% endblock %} </title> <!-- Bootstrap core CSS --> <link href="https://getbootstrap.com/docs/4.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- Custom styles for this template --> <link href="https://getbootstrap.com/docs/4.2/examples/dashboard/dashboard.css" rel="stylesheet"> </head> <body> <header> <div class ="container"> <!-- Navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark py-1"> <a class="navbar-brand p-2" href="{% url 'milk_app:home' %}">MilkStudents</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto" > <li class="nav-item"><a class="nav-link" href="{% url 'milk_app:home' %}">Home</a></li> … -
Get All checkbox value selected , Table row wise using AJAX : DJANGO
I have code which should select all rows from a table whose checkbox is selected . So first i will describe my table structure . So here there will be many rows , so i should select which server i need and which operation i should perform . So if i have two server ABC and BCD , if i want to perform start operation for ABC and Stop for ABC , i should select respective servers from first checkbox and associated operations from the checkbox on same row as the server name . and i should pass all values row wise to views.py for performing other operations . so currently I wrote a code , which give me the value even if i didn't checked the checkbox . And am not able to figure out issue . Can any anyone help me. this is my AJAX call : $("[name=ButtonSubmit]").click(function(){ var myarrayServer = []; var myarrayStart = []; var myarrayRestart = []; var myarrayStop =[]; var message = " "; $(".form-check-input0:checked").each(function() { var row = $(this).closest("tr")[0]; message += row.cells[1].innerHTML; message += " " + row.cells[2].innerHTML; message += " " + row.cells[3].innerHTML; message += " " + row.cells[4].innerHTML; var checkedValue = … -
How to execute an if statement in ManyToMany Field in Django
I am trying to check if voter already exists in database and execute a different command id the voter exists or not but my if statement returns False if there is a match in the database. My views is: def vote(request, position_id, voting_id): voter = Voter.objects.filter(pk=voting_id) print(voter) position = get_object_or_404(Position, pk=position_id) try: selected_choice = position.candidate_set.get(pk=request.POST['choice']) except (KeyError, Candidate.DoesNotExist): return render(request, 'landing/detail.html', { 'position': position, 'error_message': "You didn't select a Choice." }) else: print(selected_choice.voted_by.all()) if voter in selected_choice.voted_by.all(): print("THIS DOES") else: print("THIS DOESN'T") # selected_choice.votes += 1 # selected_choice.save() return HttpResponseRedirect(reverse('results', args=(position.id,))) When I run this, I have some print statements and it prints; <QuerySet [<Voter: BIS/2019/12345>]> <QuerySet [<Voter: BIT/2020/54321>, <Voter: BIT/2019/12345>, <Voter: BIT/2018/12345>, <Voter: BIS/2020/54321>, <Voter: BIS/2019/12345>]> THIS DOESN'T I was hoping it will print 'THIS DOES' since the voter is in the selected_choice. What might I be doing wrong -
Django- ValueError: signal only works in main thread
is it at all possible to execute Django's call_command code within or alongside Django's signals? What I have tried so far is use a ModelForm to try and update a Model class using a function based views like so: # models.py class Foo(models.Model): ... many = models.ManyToManyField("FooMany") class FooMany(models.Model): ... many = models.CharField(choices=CHOICE, max_length=2) Now, every request to update this triggers a signal that's designed to run specific tests using Django's call_command # signals.py import ntpath from my_dir import execute @receiver(m2m_changed, sender=Executor.path.through) def run_test(sender, instance, action, **kwargs): files = instance.path.all() base = [ntpath.basename(str(f)) for f in files] for file in base: execute(file) # execute function comes next # my_dir.py def execute(file): with open("executor/results/output", "w") as FILE: call_command("test", f"executor.tests.{test}", verbosity=3, interactive=False, stdout=FILE) However, these all yield a server 500 error. Further investigation yielded a ValueError: signal only works in main thread, the reason I asked if it is possible to do it this way and if not could you suggest a different approach. Thank you. -
django model's inheritance
I want to have two registration type. for example : employee and employer type. i want two different form. i override AbstractUser and after i use this class (inheritance) class User(AbstractUser): age=models.BooleanField(default=True) class employee(User): is_employee=models.BooleanField(default=True) ser=models.BooleanField() sag=models.CharField(max_length=1) class Meta: verbose_name="employee" class employer(User): is_employer=models.BooleanField(default=True) address=models.CharField(max_length=100) but when i save employee or employer class also created User class. can i do when i save only employee save just that and not User -
django static png not found
when i go to localhost/static/images.png it shows image cannot be found i have added STATIC_URL = '/static/' staticfile_dir = [static_dir, ] please ignore .html and .css and .js file is polls folder already tried pycharms default path and base_dir then changed it to os.join also tried adding static file finder -
How to capture dropdown selection into a view for conversion to excel
Hello fellow learned friends. I'd like to add a filter to a model query from a dropdown selection before converting the results to excel for download. I can't get it right since I don't know how to capture the dropdown selected item into the view. How do I get it working?? def convert_to_excel(file_name, columns, values): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(file_name) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet(file_name.capitalize()) # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() for row in values: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response def archive_to_excel(request): mark_list = Marks.objects.filter(school=request.user.school).annotate(total = \ F("eng") + F("kis") + F("mat") + F("che") + F("phy") + F("bio") + F("cre")+ F("ire")+ \ F("hre") + F("geo") + F("his") + F("agr") + F("hsc") + F("bst")+ F("mus")+ F("ger")+ F("fre"))\ .order_by('-total').annotate(mean = F('total')/15).values_list('student__name',\ 'student__adm', 'student__form__name', 'student__stream__name', 'student__kcpe','eng','kis','mat','che','phy','bio','cre','ire','hre','geo',\ 'his','agr','total','mean').order_by('-id') columns = [('name'), ('adm'),('form'),('stream'), ('kcpe'), ('eng'), ('kis'), ('mat'), ('che'), ('phy'), ('bio'), ('cre'),\ ('ire'), ('hre'), ('geo'), ('his'), ('agr'),('total'),('mean') ] return convert_to_excel("Marks", columns, mark_list) -
How to filter objects according to the selected month in Django?
I have a Customer model. This model has a created_date field. I want to list all customers created in the selected month. I think I can use timedelta for that but I cannot figure out how can I applied that. How can I filtering the customers according to the selected month? views.py def log_records(request): .... form = MyForm() if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): cd = form.cleaned_data months = cd.get('months') selected_month = datetime.today() - timedelta(days=...somethin...) selected_month_customers = Customer.objects.filter(company=userP[0].company, created_date__gte=last_month.count() ... context = {'selected_month_customers': selected_month_customers,...} return render(request, 'logs.html', context) models.py class Customer(models.Model): ... created_date = models.DateTimeField(auto_now_add=True) ... forms.py class MyForm(forms.Form): MONTH_CHOICES = [ ('January', 'January'), ('February', 'February'), ('March', 'March'), ('April', 'April'), ('May', 'May'), ('June', 'June'), ('July', 'July'), ('August', 'August'), ('September', 'September'), ('October', 'October'), ('November', 'November'), ('December', 'December'), ] months = forms.CharField(widget=forms.Select(choices=MONTH_CHOICES), label="Select a month ") -
hardcoded url issue when drag & drop images with django-markdownx through S3
My website works perfectly fine with django-markdownx, unless I upload images. When I drag and drop image on markdownx form, auto generated image url is added in form like below: As you see, image is shown just fine. My storage is AWS s3, and I'm using private bucket. The problem occurs, however, an hour later. In the markdown url query parameter X-Amz-Expires=3600, which is an hour. So after that the url is no longer valid, saying request has expired. This is another expired url, but you get the idea. I use django-storages, boto3, AWS S3 for file storages. According to django-storages doc, AWS_QUERYSTRING_EXPIRE (optional; default is 3600 seconds) The number of seconds that a generated URL is valid for. I might extend expiry time like super long as suggested in other post in SO, but doesn't that mean I should update at least once every super long time period? That doesn't seem the right way. Some suggested making S3 bucket public, but I don't want allow anyone to download my image. I delved in django-markdownx doc and github, without making much progress. How can I get dynamically made presigned url when uploading image using djang-markdownx? Let me know if I'm … -
FieldDoesNotExist error with django-mongoengine?
I want to use mongoDB as my primary database in my new django (v 3.1.2) project. So far I have not created any models and only created a django project with one app and then installed pip install django-mongoengine. I then edited my settings.py file and included these custom codes. Mongodb is running as a service in my system. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'django_mongoengine', 'django_mongoengine.mongo_auth', 'django_mongoengine.mongo_admin', ] # MongoDB settings MONGODB_DATABASES = { 'default': {'name': 'django_mongoengine'} } DATABASES = { 'default': {'ENGINE': 'django.db.backends.dummy'} } AUTH_USER_MODEL = 'mongo_auth.MongoUser' AUTHENTICATION_BACKENDS = ( 'django_mongoengine.mongo_auth.backends.MongoEngineBackend', ) SESSION_ENGINE = 'django_mongoengine.sessions' But when I started my server python manage.py runserver I am getting this error File "/home/Eka/.virtualenvs/Env/lib/python3.6/site-packages/django_mongoengine/forms/document_options.py", line 4, in <module> from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' I also tried to import django_mongoengine using a different terminal, which also yield the same error. How can we solve it? -
Django: How to retrieve a Queryset of the latest, uniquely named records with a MySQL database
I require a query that can search my model for the latest, unique records and return a queryset of the results. I need distinct on setup_name and latest on updated models.py class VehicleSetupModel(models.Model): inertia = models.IntegerField() tyre_pressure = models.IntegerField() class StandardVehicleSetupModel(VehicleSetupModel): setup_name = models.CharField(max_length=20) updated = models.DateTimeField(auto_now=True) vehicle = models.ForeignKey(VehicleModel, on_delete=models.CASCADE) What I've tried I tried the following: StandardVehicleSetupModel.objects.all().order_by('updated').distinct('updated') but MySQL does not support DISTINCT ON querys. Table Layout (DD-MM-YYYY) setup_name | updated | vehicle ---------------------------------------------------------- TEH 10-10-2020 1 TEH 11-10-2020 1 TEL 10-10-2020 1 TEL 08-10-2020 1 TEL 01-10-2020 1 TEP 01-10-2020 1 Expected Result (DD-MM-YYYY) setup_name | updated | vehicle ---------------------------------------------------------- TEH 11-10-2020 1 TEL 10-10-2020 1 TEP 01-10-2020 1 -
import models from another directory
I'm new in Django. i am following a tutorial and now i have a problem . my directory tree is like and in /pages/views i have this from django.http import HttpResponse from django.shortcuts import render def home_view(*args, **kwargs): return "<h1>Hello world</h1>" and in urls.py i have this from django.contrib import admin from django.urls import path from pages.views import home_view urlpatterns = [ path('', home_view, name='home'), path('admin/', admin.site.urls), ] ***but it can't recognize pages *** i also tried these solution but didn't work!what do i missing? even i added these codes to settings.py import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(BASE_DIR, 'pages')) { django 3.1 } -
django- django admin Modify External Model Field Name
I added fields from existing models(ProUser), fields from external models(Point) to Admin. @admin.register(ProUser) class ProUserAdmin(admin.ModelAdmin): list_display = [ "id", "user_nm", "user_ty", "user_tel", "user_email", "point_amt", **One of the fields in the 'Point' model, not in the 'ProUser' model** "user_join_dts", ] In ProUser's model, [user_nm = models.CharField ("app user name", max_length=10)] As such, the field name "app user name" was specified. Therefore, the field name appears to be [app user name] instead of [user name] in Admin. As such, I would like to name the fields imported from the Point model. For now, [pointamt] is the name of the field. I want the field "point_amt" to be the field name "user point" in Admin. Is there a way?