Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why use aggregate to find average value instead of using tutal_sum/n in django
Here we calculate using aggregate >>> avg = Book.objects.aggregate(average_price=Avg('price')) {'average_price': 34.35} But why we don’t use below concept in above. a = Books.objects.all() Avg = sum([x.price for x in a])/len(a) 34.35 I want to know use aggregate rather than second procees. -
'UserManager' object has no attribute 'validate'
My usual registration and login validators stopped working and I'm banging my head against the wall trying to figure out why. This is the error: AttributeError at /register 'UserManager' object has no attribute 'validate' Models.py class UserManager(models.Manager): def validate(self, postData): errors = {} if len(postData['first_name']) < 3: errors['first_name'] = 'First Name must be at least 2 characters' if len(postData['last_name']) < 3: errors['last_name'] = 'Last Name must be at least 2 characters' EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') if not EMAIL_REGEX.match(postData['email']): errors['email'] = "Invalid email address!" email_check=User.objects.filter(email=postData['email']) if email_check: errors['email'] = ("Email address already taken!") if len(postData['password']) < 8 : errors['password'] = 'Password must be at least 8 characters' if postData['password'] != postData['confirm_password']: errors['password'] = 'Passwords do not match' return errors views.py def register(request): if request.method == "GET": return redirect('/') errors = User.objects.validate(request.POST) if errors: for e in errors.values(): messages.error(request, e) return redirect('/') else: new_user = User.objects.register(request.POST) request.session['user_id'] = new_user.id return redirect('/profile') -
Django template text to views. Py
Is there any way in django to extract the text inside any paragraph of template to the django views. Py file. Or If there is no post and get method. -
i am using django to return file as response but i want to return mutiple files or zip how i can do it [duplicate]
here is the simple code where after returning 1 files the function get returned how can we make it recursive or any help. @login_required(login_url="/login/") def download(request): FileData = File.objects.filter(project=projectId) for i in FileData: filePath = settings.MEDIA_ROOT+i.files with open(filePath,"rb") as fh: response = HttpResponse(fh.read(),content_type="application/files") response["Content-Disposition"]= "inline;filename="+os.path.basename(filePath) return response return HttpResponse("something error") -
Why my model field doesn't read the value of its ForeignKey, it returns its object number instead?
I created a model which has a field which I want to be a dynamic dropdown. I created another model and related them with a Foreign Key. Now everything works fine except the dropdown doesn't show the values from the other model, instead it returns its numbered objects. Here is my models.py: from django.db import models from django.core.validators import RegexValidator from django.db.models.deletion import CASCADE # Create your models here. class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) class InitialData(models.Model): pattern = RegexValidator(r'RT\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') pattern1 = RegexValidator(r'OOPL\/D\/00[0-9]', 'Enter Case Number properly!') case_number=models.CharField(max_length=10, primary_key=True, unique=True, validators=[pattern1], blank=True) date_of_admission=models.DateField(default=None) date_of_discharge=models.DateField(default=None) name=models.CharField(max_length=100, default=None) mr_uid=models.IntegerField(default=None) rt_number=models.CharField(max_length=15, blank=False, validators=[pattern], default=None) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) forms.py: class TrackReportForm(ModelForm): class Meta: model=InitialData fields=('case_number', 'date_of_admission', 'date_of_discharge', 'name', 'mr_uid', 'rt_number', 'diagnosis') class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields=('diagnosis',) views.py: def initialview(request): if request.method=='POST': fm_diagnosis=DiagnosisForm(request.POST) fm_initialdata=TrackReportForm(request.POST) if fm_diagnosis.is_valid() and fm_initialdata.is_valid: diagnosis=fm_diagnosis.save() initial=fm_initialdata.save(False) initial.diagnosis=diagnosis initial.save() fm_diagnosis=DiagnosisForm() fm_initialdata=TrackReportForm() return render(request, 'account/database.html', {'form1':fm_diagnosis, 'form2':fm_initialdata}) else: fm_diagnosis=DiagnosisForm() fm_initialdata=TrackReportForm() return render(request, 'account/database.html', {'form1':fm_diagnosis, 'form2':fm_initialdata}) URLs: from account import views urlpatterns = [ path('admin/', admin.site.urls), path('data/', views.initialview), ] template: <body> <form action="" method="post" novalidate> {% csrf_token %} {{form1.as_p}} {{form2.as_p}} <button type="submit">Save</button> </form> </body> What needs to be changed? -
how to verify username and password at the time of login where existing password is encrypted by make_password which is stored in database?
I have register username and password using the following code views.py def registerPage(request): if request.method == 'POST': form = AdminUserForm(request.POST) Password = request.POST['Password'] if form.is_valid(): user = form.save(commit=False) user.Password = make_password(Password) user.save() messages.success(request, "user created succesfully!!! login now") return redirect('login') else: form = AdminUserForm() return render(request, 'signup.html', {'form': form}) Can someone tell me how to verify username and password while login, and logout? models.py class AdminUser(models.Model): Id=models.AutoField(primary_key=True) Name=models.CharField(max_length=100, null=False, blank=False) Username=models.CharField(max_length=100, null=False, blank=False) Password=models.CharField(max_length=100, null=False, blank=False) class Meta: db_table='admin_users' forms.py class AdminUserForm(forms.ModelForm): class Meta: model= AdminUser fields = '__all__' thanks in advance, please help in login and logout -
Why try except not works in django filter?
Here is my filter class: class PackageFilter(django_filters.FilterSet): regex = django_filters.CharFilter(method="regex_filter") class Meta: model = models.Package fields = { 'package': ['exact'], } def regex_filter(self, queryset, _, value): try: return queryset.filter(package__regex=value) except: raise ParseError('{} is invalid regex!'.format(value)) when i deliver python-2.\d+* to backend backend should return 400 python-2\.\d+* is invalid regex! but actually not, it return File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py" in exit 89. raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) Exception Type: DataError at /api/v3/packages/ Exception Value: invalid regular expression: quantifier operand invalid -
Getting multiple textfield values - Javascript/Django
This is my code. I'm trying to get all the values from the dynamically generated textboxes so that I can average them and will use the value later. Is there any easy way to get all the values and their average? for(var i = 0; i < input_list.length -1; i++) { var label_input = document.createElement('label'); label_input.innerHTML = input_list[i+1]; document.getElementById("newElementId").appendChild(label_input); for(var j = 0; j < 5; j++) { $('#newElementId').append("<div><input type='textbox' id='"+ input_list[i+1] + j +"' /></div>"); } } -
Why do some model objects reset every time i redeploy and after a while of time passes in Django Heroku?
This is probably a really dumb question. Every time I redeploy my django app on heroku i get the same two instances of my object that were there before i deployed. I would like to change these. I would like to add some. I would like to delete some. But every time I redeploy, and after some time passes after I make changes, it always reverts back to what it was. It is horrible. Please let me know what I am doing wrong. NOTE: I AM ALREADY HOLDING MY FILES SOMEWHERE ELSE. I don't believe this has anything to do with the ephemeral file system, since I already am storing files somewhere else. But why is it that every time I redeploy the instances of the objects themselves (instances of the things inside Models) go away?? Thanks in advance. -
'TypeError' object has no attribute ''
I am using SendGrid with Django and I have two separate functions. One works using the SendGrid code (See below - Working Code) and then the other keeps getting the Error - 'TypeError' object has no attribute 'booking_message'. I imagine the issue is something small and I keep missing it. Appreciate any help I can get on this. (Note - I have taken out the template id's, From and to email addresses and SendGrid API App id and just let '') I did not have time to use an environment variable to hide the keys before posting. Working code class ASPBookingsCreateView(CreateView): form_class = ASPBookingsForm model = ASPBookings template_name = "vistours/asp.html" def post(self, request): # Save the new booking to the database. if request.method == 'POST': form = ASPBookingsForm(request.POST) if form.is_valid(): print(request.POST) form.save() # Get the data for the emails. asp_data = ASPBookings.objects.all() asp_data.contact_name = request.POST['contact_name'] asp_data.booking_email = request.POST['email'] asp_data.booking_date = request.POST['booking_date'] asp_data.booking_time = request.POST['booking_time'] asp_data.program_type =request.POST['program_type'] # Format Date and Time formatted_date = parse_date(asp_data.booking_date).strftime('%A %d %B %Y') print(formatted_date) # Add SendGrid Template ID's BOOKING_TEMPLATE_ID = '' UPDATE_TEMPLATE_ID = '' # Send confirmation email of the booking. booking_message = Mail(from_email='', to_emails=[asp_data.booking_email], ) # Add Template ID to booking message. booking_message.template_id = … -
how do I produce m2m model from sql schema?
I am new with django ecosystem where I want to create the following tables from SQL to django model syntaxis where I got stuck at how to produce this proxy table tools_x_techniques as m2m CREATE TABLE tools_x_techniques ( # m2m id INTEGER PRIMARY KEY AUTOINCREMENT, tool_id TEXT NOT NULL, technique_id TEXT NOT NULL, FOREIGN KEY (tool_id) REFERENCES tools (id), FOREIGN KEY (technique_id) REFERENCES technique (id) ); CREATE TABLE tools ( id INTEGER PRIMARY KEY AUTOINCREMENT, tool_id TEXT NOT NULL, ); CREATE TABLE techniques ( id INTEGER PRIMARY KEY AUTOINCREMENT, technique_id TEXT NOT NULL, ); django class Techniques(models.Model): technique_id = models.TextField() class Tools(models.Model): tool_id = models.TextField() -
ERROR: Command errored out with exit status 1: 'import sys, setuptools, tokenize; sys.argv[0]
how to solve this problem. I am tried to solve the error can't properly deploy my Django project on Heroku build logs: | ^~~~~~~~~~~~~~~~~~~~~ error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-zu1munoh/typed-ast/setup.py'"'"'; __file__='"'"'/tmp/pip-install-zu1munoh/typed-ast/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-s15khtlb/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/typed-ast Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed Procfile web: gunicorn My_Ecom_Project.wsgi -
Server Request Interrupted Heroku
I am using React Native and Django. Everything was working fine, until I made a request and I got the following error: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/api/obtain-img" host=notarealapp.herokuapp.com request_id=... fwd="..." dyno=web.1 connect=0ms service=22ms status=503 bytes=316 protocol=https Also, I don't know if this is useful information, but I got the following error too: <rest_framework.request.Request: POST '/api/obtain-img'> The fetch code I used is this: let token = await SecureStore.getItemAsync("token"); console.log(uri); let filename = uri.split("/").pop(); let match = /\.(\w+)$/.exec(filename); let type = match ? `image/${match[1]}` : `image`; let formData = new FormData(); formData.append("image", { uri: uri, name: filename, type: type }); // formData.append("cateogry", category); // formData.append("mission", value); console.log(formData); return await fetch("https://notarealapp.herokuapp.com/api/obtain-img", { method: "POST", headers: { "content-type": "multipart/form-data", Authorization: `JWT ${JSON.parse(token)}`, }, body: formData, }) .then((res) => res.json()) .then((json) => console.log(json)) .catch((error) => console.error(error)); And my Django code is the following: class ObtainImageUri(APIView): permission_classes = [IsAuthenticated] def post(self, request, format=None): print(request) return Response({"succes": "The receipt was stored successfully."}, status=200) I am open to any help. Thank you -
IntegrityError: UNIQUE constraint failed: auth_user.username - Django
I have a sample application that simply logs in and registers users. I am adding functionality for checking whether a username is already taken. For that, in the form code, I put a validation function as is usual in django. It's called clean_username. There are also functions like clean_email and clean to check the sanity of data. While the other two work just fine to weed duplicates, the clean_username function is particularly erroneous. Though I have added a line to check whether the username already exists, it still throws the same Integrity Error, which is exactly what I am trying to avoid. The clean_username function is of our concern here. Note: The print statements are only added for debugging purposes. Please find the code below (forms.py): from django import forms from django.forms.widgets import Widget from django.contrib.auth import get_user_model from email_validator import validate_email, EmailNotValidError from .constants import countries User = get_user_model() class RegisterForm(forms.Form): login = forms.CharField(label="Username:") password = forms.CharField(label="Password", widget=forms.PasswordInput()) confirm_password = forms.CharField(label="Confirm Password:", widget=forms.PasswordInput()) email = forms.EmailField(label="Email") def clean_username(self): print(f"Clean Username data: {self.cleaned_data}") username = self.cleaned_data.get("login") print("cleaning username...") existing_user_set = User.objects.filter(username=username) if existing_user_set.exists(): raise forms.ValidationError("Username is taken!!") return username def clean(self): data = self.cleaned_data print(f"\n\nData from cleaned data: {data}") password … -
Include a .html file in Django template that is located in a different directory
Let's say I have the following directory structure |-data |-include_this.html |-app |- templates |- app |- page.html In page.html, I'd like to include the include_this.html file contained in the data folder. I have tried the following: {% include '../data/papercups.html' %} {% include '../../data/papercups.html' %} {% include './../data/papercups.html' %} But none of them seem to work, and the second one throws the error: The relative path points outside the file hierarchy that template is in. What's the correct way to do this? -
axios wont retrieve data from django server
I try to retrieve data from my django server to render it with react but I encountered a probem: The data doesen't render. I have my django server running in localhost:8000 and react app running in localhost:3000 my App.js: import React from 'react'; import axios from 'axios'; class App extends React.Component { state = { details : [], } componentDidMount() { let data ; axios.get('http://localhost:8000/wel/') .then(res => { data = res.data; this.setState({ details : data }); }) .catch(err => {}) } render() { return( <div> {this.state.details.map((detail, id) => ( <div key={id}> <div > <div > <h1>{detail.detail} </h1> <footer >--- by <cite title="Source Title"> {detail.name}</cite> </footer> </div> </div> </div> ) )} </div> ); } } export default App; and my server page where I try to retrieve data from: localhost:8000/wel what's going on? -
Redis Error condition on socket for SYNC: Connection refused
Using celery with redis in my django app Everything was working fine until I ran into a problem. The location of the redis files was changed and redis could not access them. After searching, it turns out that this is due to random attacks on the Internet, and it is necessary to add confg After I added the file, they both worked fine for a while, and then this problem appeared 1:S 25 Jun 2021 00:48:12.029 # Error condition on socket for SYNC: Connection refused 1:S 25 Jun 2021 00:48:12.901 * Connecting to MASTER 194.38.20.199:8886 1:S 25 Jun 2021 00:48:12.902 * MASTER <-> REPLICA sync started 1:S 25 Jun 2021 00:48:13.034 # Error condition on socket for SYNC: Connection refused 1:S 25 Jun 2021 00:48:13.907 * Connecting to MASTER 194.38.20.199:8886 1:S 25 Jun 2021 00:48:13.908 * MASTER <-> REPLICA sync started 1:S 25 Jun 2021 00:48:14.041 # Error condition on socket for SYNC: Connection refused When I rebuild the Redis container it runs for a very short time and I get the same problem settings.py CELERY_BROKER_URL = os.environ.get("redis://redis:6379/0") CELERY_RESULT_BACKEND = os.environ.get("redis://redis:6379/0") docker-compose.yml redis: image: 'redis:alpine' restart: unless-stopped command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./docker/redis/redis.conf:/usr/local/etc/redis/redis.conf ports: - '6379:6379' celery: restart: unless-stopped build: … -
How to allow only a certain section of my code to reload in Django
So, I am using a Django application where I am using the google maps API as well. So this is the instance...when I submit a form... I only want my form div to reload and NOT the div where my map lies. So my code is... <section class="middleSection p-2"> <div class="HideOpenMiddleCont justify-content-center" onclick="HideOpenMiddleCont()"> <div class="px-4 rounded-pill bg-warning" id="arrowCont"> <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" class="bi bi-arrow-down-short text-dark" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M8 4a.5.5 0 0 1 .5.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5A.5.5 0 0 1 8 4z"/> </svg> </div> </div> {% if view == 'trip' %} {% include "app/passenger/trip.html" %} {% elif view == "upcomingRides" %} {% include "app/passenger/upcomingRides.html" %} {% elif view == "pastRides" %} {% include "app/passenger/pastRides.html" %} {% endif %} <div class="optionBarPull" data-bs-toggle="offcanvas" href="#offcanvasExample" role="button" aria-controls="offcanvasExample"> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-arrow-right-circle-fill" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z"/> </svg> </div> </section> <section class="rightSection" id="map"> <h3 class="font3 text-center p-2"><strong>Google Maps is here</strong></h3> <h4 class="font3 text-center … -
JavaScript variable doesn't loop through Django model
Topic is a CharField, summary is TextField within topic. For some reason, the JavaScript doesn't loop through summary TextField -- it just uses the very first summary TextField and simply ignores the rest. I want every summary TextField to looped through and displayed. Not just the first one. Does this make sense? Something is wrong with my JavaScript code. As you can see in the image -- second topic's (Bitcoin) summary is missing (highlighted in red) Image displaying the problem on the webpage {%for topic in topics%} <script> var i = 0; var txt = '{{topic.summary}}'; function typeWriter() { if (i < txt.length) { document.getElementsByClassName('js-typewrite')[0].innerHTML += txt.charAt(i); i++; setTimeout(typeWriter, 65); } } setTimeout(typeWriter, 1000); </script> <body> <p class="content"> <span class="typewrite anim-typewrite js-typewrite"></span> </p> </body> </div> <div id = 'mpost-text'> {{topic.text|linebreaks}} </div> <div id = 'change-text'> {%if topic.owner == request.user and user.is_authenticated %} <a href = "{%url 'new_sites:post_edit' topic.id%}">Edit entry</a> <a href = "{%url 'new_sites:delete_post' topic.id%}">Delete topic</a> {% endif %} </div> </div> {%empty%} <li>No topics have been added yet.</li> {% endfor %} {%if user.is_authenticated%} <a href="{% url 'new_sites:new_post'%}">Add Post</a> {%endif%} {%endblock%} -
loading local files in django
I have a folder in c:\images, images here are updated by another app. Then I wanted a Django application to read those images on the admin site. The django applicationis sitting in c:\inetpub\wwwroot\myapp I have tried adding below lines in settings.py CURRENT_PATH = os.path.abspath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(CURRENT_PATH, '../../images').replace('\\','/') MEDIA_URL = 'images/' I also tried including the whole path in django admin as below in admin.py def img_field(self, obj): return format_html('<img src="{}" width="500" height="500" />'.format("c:\images\phot1.png")) If i put online image link it works fine as below: def img_field(self, obj): img = "https://www.thebalancesmb.com/thmb/5G9LJXyFzbTVS-Fj_32sHcgJ8lU=/3000x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/start-online-business-with-no-money-4128823-final-5b87fecd46e0fb00251bb95a.png" return format_html('<img src="{}" width="500" height="500" />'.format(img)) How can i get around this? -
Assign permissions to users without admin-site
Im creating a custom role-based user-management system for my Django application. I want to know, if there is a way to assign permission to Django users via roles, without using the admin-site, because when the app gets deployed, the admin-site gets "deactivated". My idea was to use a one-to-one relationship with a role-model, which extends the PermissionsMixin class and for each new role, I define a list of permissions. Whenever the has_perm() function of an user gets called, I use the has_perm() function of the linked role. I have to point out, that the roles are also used to store specific information not related to the authentication process. -
Create a django background worker, best practices
I have an API in Django, which should consume a RabbitMQ queue. I'm currently using Amqpstorm Robust Consumer, instantiated by django command management, like this: python3 manage.py mycommand. and API runs in another container using gunicorn. My queue has a high message rate coming I. My concern is if this is the best practice to run this kind of process in the background with django. Is there a better way to run this worker? I say this because my container is closing sporadically, without logging anyone, just this message: Logs Killed. -
Django admin inline - show different read-only fields based on the user and the object
Django 2.2.24. I have an inline that I want to show different read-only fields based on the user's group and a field on the model. I tried to adapt the simple methodology I used on the model's admin page: class MyObjectInline(admin.StackedInline): ... def get_readonly_fields(self, request, obj=None): fields = super(self.__class__, self).get_readonly_fields(request, obj) if obj: if request.user.groups.filter(name=SPECIAL_GROUP).exists(): if obj.tag == SPECIAL_TAG: fields += (...) else: fields += (...) return fields This doesn't work bc of the well-known issue (bug?) that the object in the inline is the parent object for the whole admin page and not the object actually represented in the inline. In researching work-arounds, it seems like a custom form is required for the inline, and then a combination of __init__ and a clean routine for each field on the model is required? But I'd also need to pass the request object into the form, which research suggests incorporating a FormSet and/or FormFactory as well? As the complexities pile up, any advice on the right way to accomplish this would be appreciated! Thanks. -
Django pass PK from post to next page
I currently have a blog post feature on my site. I want users to be able to create sub posts (build log ) off of the main posts. I created this model with a FK to the Post model class BuildLog(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) I then added a button on the post page and created a form. Everything is working as expected but when I submit the form I get the error null value in column "post_id" of relation "blog_buildlog" violates not-null constraint If I understand the error correctly it is saying I am not passing the PK of the post into the form. Views def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) form = CommentForm comments = Comment.objects.filter(post=post)#.order_by('-create') if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.author = request.user new_comment.post = post new_comment.save() context = { 'post':post, 'form':form, 'comments':comments } return render(request, 'blog/post_detail.html', context) class BuildLogView(LoginRequiredMixin, CreateView): model = BuildLog form_class = BuildLogForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def save(self, *args, **kwargs): super(BuildLog,self).save(*args, **kwargs) Url path('build-log-form/', BuildLogView.as_view(), name='build-log-form'), path('post/<int:pk>/', views.DetailPostView, name='post-detail') … -
Django many to many relationship only shows on one model in the admin
I’m new to python and django and have set a many:many relationship between the Subscriber and Tag classes (i.e. one subscriber can have many tags, and one tag can have many subscribers). In the django admin panel, viewing a tag successfully shows the connected subscribers as follows: However, viewing a subscriber does not show the tags they’re associated with: It’s like the many:many relationship is not shown on both sides. I’ve read some other similar django posts creating inlines and functions etc, but to no avail - and I want the tags to show only on the individual subscriber page rather than a column in the table before clicking on an individual subscriber. How can I get the tags to show on the individual subscriber pages? I tried with inlines but to no avail. Models.py: from django.db import models from accounts.models import Account class Subscriber(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True) # tags: many to many field, with later option of users being able to define custom tags # tags = models.ManyToManyField(Tag, blank=true) # cannot uncomment, otherwise error: "NameError: name 'Tag' is not defined" - but already has many:many relationship - just not showing …