Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Regarding user authentication
When the user is logged in or logged out the user must see and can fill the feedback page.How can I do it?Feedback page -
Sending Mail configuration in django
I am facing a problem when trying to test sending a message from the django app, but I get this error message : SMTPAuthenticationError at /accounts/contact_us (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f13sm16175910wrt.86 - gsmtp') And I looked for all the possible solutions like : Enable two-step verification , Enable less secure app access settings . But it was in vain and did not work successfully. Could anyone help please ? this is my settings : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myname@gmail.com' EMAIL_HOST_PASSWORD = '****************' EMAIL_USE_TLS = True EMAIL_PORT = 587 this is my views.py: def contact_us(requset): subject = requset.POST.get('subject', '') message = requset.POST.get('message', '') from_email = requset.POST.get('from_email', '') send_mail(subject, message, from_email, ['myname@gmail.com']) return render( requset , 'accounts/contact_us.html' ) this is my contact_us.html: <div class="contact_form"> <form name="contact_form" action="" method="POST"> {% csrf_token %} <p><input type="text" name="subject" class="name" placeholder="subject" required></p> <p><textarea name="message" class="message" placeholder="message" required></textare></p> <p><input type="text" name="from_email" class="email" placeholder="email" required></p> <p><input type="submit" value="sent" class="submit_btn"></p> </form> </div> -
djang_.template_exception_TemplateDoesNotExist
TemplateDoesNotExist at /manager manager/templates/login.html Request Method: GET Request URL: http://127.0.0.1:8000/manager Django Version: 3.1.1 Exception Type: TemplateDoesNotExist Exception Value: manager/templates/login.html Exception Location: C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['E:\Project\Debugger', 'C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Microsoft\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\lib\site-packages', 'C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32', 'C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32\lib', 'C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\lib\site-packages\Pythonwin'] Server time: Sun, 20 Jun 2021 13:58:39 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: E:\Project\Debugger\templates\manager\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\manager\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Microsoft\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\manager\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: E:\Project\Debugger\manager\templates\manager\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: E:\Project\Debugger\welcome\templates\manager\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Microsoft\AppData\Roaming\Python\Python37\site-packages\phone_field\templates\manager\templates\login.html (Source does not exist) -
How can i update a field in django with javascript
my project is about bidding when the product time is up then it should be automatically saved to a orders table please help me to solve with any way that you know models.py class products(models.Model): produtname=models.CharField(max_length=255) productdesc=models.CharField(max_length=255) amount=models.FloatField() image=models.ImageField(upload_to='pics') featured=models.BooleanField(default=False) enddate=models.DateTimeField() class orders(models.Models): product_id=models.IntegerField() user_id=models.IntegerField() i wanted to update the orders table automatically when the products tables endate is finished can you please suggest me any way to do this. -
Django import export when we have name of data when importing foreign key but not the id
I am having a csv file with the data which includes name of the user who will import the data, which is basically a foreign key. When I try to import the csv file. I am not able to import the csv file with the name of the foreign key (with the username of the user) . This is my models.py where I am taking a field which will take the input of the logged in user if the form is filled via UI. However to import the data in bulk, I should be able to give the username of the user who is importing the data and not the foreign key which is an integer value. models.py class Vendor(models.Model): ... added_by_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name= "vendors", verbose_name="Added By User") ... This is my admin.py from django.contrib import admin from app.models import Vendor from import_export import resources from import_export.admin import ImportExportModelAdmin from django.contrib.auth.models import User class VendorResource(resources.ModelResource): class Meta: model = Vendor fields = ('added_by_user__username',) @admin.register(Vendor) class VendorAdmin(ImportExportModelAdmin): pass I am new to this and I think I am missing on something, I have followed everything as mentioned here in documentation. Please help me find the correct option so that … -
Creating django notifications using signals
I am trying to create django notifications using signals. Any user can add a question, add a solution to that question and comment on each solution. So I have this in models.py: class Log(models.Model): title = models.CharField(blank=False, max_length=500) content = models.TextField(blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): super().save() self.slug = self.slug or slugify(self.title + '-' + str(self.id)) super().save(*args, **kwargs) class Meta: verbose_name = ("Log") verbose_name_plural = ("Logs") def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("log-detail", kwargs={"question": self.slug}) class Notification(models.Model): notification_for = models.CharField(null=True, blank=True,max_length=50) user = models.ForeignKey(Log, on_delete=models.CASCADE,null=True, blank=True) I want to create notification when someone adds a question, or solution or comments Do I have to create separate Notification model for each type of notif? signals.py: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Log, Notification @receiver(post_save, sender=Log) def create_notif(sender, instance, created, **kwargs): if created: Notification.objects.create(author=instance.author, notification_for='log created') -
get results of running a task on Celery (Windows 10 32 bits)
I've been working around this problem for about 10 hours since morning but couldn't find any solutions to that. I'm learning to use Celery. I want to use it in one of my django projects. I followed the official tutorials but I can't get the results of my tasks back. no matter the backend is configured or not, I always get this error when trying to access the results: Traceback (most recent call last): File "<console>", line 1, in <module> File "G:\progs\python\Django-projects\celery_tutorial\env\lib\site-packages\celery\result.py", line 223, in get return self.backend.wait_for_pending( File "G:\progs\python\Django-projects\celery_tutorial\env\lib\site-packages\celery\backends\base.py", line 698, in wait_for_pending meta = self.wait_for( File "G:\progs\python\Django-projects\celery_tutorial\env\lib\site-packages\celery\backends\base.py", line 1029, in _is_disabled raise NotImplementedError(E_NO_BACKEND.strip()) NotImplementedError: No result backend is configured. Please see the documentation for more information. Here is my folder structure: |- task_exe |- celery.py |- settings.py |- ... |- tadder |- tasks.py |- ... |- env |- manage.py |- ... this is my celery.py file: from __future__ import absolute_import, unicode_literals from celery import Celery from tadder.tasks import add import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'task_exe.settings') app = Celery("task_exe", backend='rpc://' , broker='amqp://localhost') app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() this is my tasks.py file: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(a, b): return a + b and this is the … -
How to access database table with primary key in Django SQLite3 database
In my Django app, I'm adding a search feature that will search the posts database and return matching results. After a few Google searches, I discovered that we can search using "example contains='example'." It works, but it only returns the title of the results; I can't figure out how do I get the description of a post whose title I know? This is the source code: views.py: def results(request): match_title = Posts.objects.filter(Q(title__contains='Pets')) context = { 'results': match_title } return render(request, 'blog/results.html', context) models.py: class Posts(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length = 100) desc = models.CharField(max_length = 1000) def __str__(self): return f'{self.title}' results.html: {% if links %} {% for result in results %} <div class="result-group results-container"> <small class="result-link">{{ result.url }}</small> <h2 class="result-title">{{ result.title }}</h2> <h5 class="result-desc">{{ result.desc }}</h5> </div> <br> {% endfor %} {% else %} <div class="result-group results-container"> <p>Sorry, we are not able to find what you are looking for.</p> </div> {% endif %} How do I get the description of a post whose title I know? Please assist. -
django validating a field even when a depending field is empty
I am trying to validate two depending fields such that, if a checkbox is checked, then validate the URL field, but if the checkbox is not checked, do not validate the URL field. Using clean() I have a code that looks like this: models.py class MyModel(models.Model): chkbk = MultiSelectField(max_length=15, choices=choices.SOME_CHOICES, blank=True, null=True) url_field = models.URLField(max_length=200, blank=True, null=True) form.py def clean(self): cleaned_data = super().clean() chkbk = cleaned_data.get('chkbk') url_field = cleaned_data.get('url_field') if chkbk and url_field is None: self.add_error('chkbk', ValidationError("Fix this error")) The logic works if the user checks box and submit a valid URL the user checks box and leaves url field empty, error message the user unchecks box and leaves url field empty But, when the user unchecks the box but have invalid url in the url field, the for does not submit, because regardless of the validation checks, the url field will still try to submit to the database, which is an expected behaviour. Is there a way to not validate the URL field if checkbox is unchecked or set the value of that field to empty/null/None in clean just before submitting the form so validation on the url field can pass if the checkbox it depends on is not … -
how to filter on a reversed relationship on Django?
I have this two models: class Company(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField() class Employee(models.Model): name = models.CharField(max_length=255) incorporated_at = models.DateTimeField() company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="employees") If I do the following reversed lookup: Company.objects.filter(employees__incorporated_at="2021-01-01T00:00:00+00:00") Then I'll get a list of those companies with at least one employee that satisfies such a query. But what I want to get is a list of companies with all its employees satisfying that query. How can I do it? -
Django Pyrebase retrieving from firebase using infinite scroll
I'm a bit stuck on how best to approach this problem. I currently have data being pulled in from Firebase and use django paginator with jquery and waypoints to get an infinite scroll. However, the def innovations_view currently returns all the entries in the database. I want it to return the first 5 then on scroll load another 5. I believe I may need to add a listener, but not sure how best to approach it. Any help would be greatly appreciated. views.py def innovations_view(request): db_name = database.child('1aBDytzaM232X_H3tjTuanG8-jxiEn0rg5_pg_cvnbgw') object_list = db_name.child('Sheet1').get().val() page = request.GET.get('page', 1) paginator = Paginator(object_list, 5) try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) context = { "object_list": objects, } return render(request, 'list.html', context) list.html {% extends 'base.html' %} {% block content %} {% load static %} <div class="container-fluid"> <div class="row row-cols-1 row-cols-md-3 g-4 infinite-container"> {% for instance in object_list %} <div class="col infinite-item"> <div class="card h-100"> <img src="{{ instance.featureimg}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ instance.title }}</h5> <p class="card-text">{{ instance.summary|truncatewords:20 }}</p> </div> </div> </div> {% endfor %} </div> <div class="spinload position-fixed" style="display: none; top:35vh; left:46vw;"> <div class="spinner-border" role="status"> <span class="visually-hidden">Loading...</span> </div> </div> <div> {% if object_list.has_next %} <a class="infinite-more-link" href="?page={{ … -
i want to generate short link and render it to templates using pyshorteners
I want to convert my full url to short url using pyshorteners and render to every detail templates of the link . Here, i am giving below, the views and the link template, with the url patterns. Below is my Views.py: import pyshorteners def get_absolute_url(request): link = request.get_full_path() shortener = pyshorteners.Shortener() short_link = shortener.tinyurl.short(link) return reverse('link', {"link": short_link}) Below is my Link Template: <!-- Copy to Clipboard --> <center> <label for="text_copy" class="text-primary">Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy" value="{{ request.build_absolute_uri }}"/> <div class="container"> <button onclick="copyToClipboard('#text_copy')" type="button" class="col mr-3 btn btn-light btn-rounded" data-mdb-ripple-color="dark">Copy</button> </div> </center> <!-- Copy to Clipboard --> <center> <label for="text_copy" class="text-primary"> Short Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy1" value='{{ link.short_link }}'/> <div class="container"> <button onclick="copyToClipboard('#text_copy1')" type="button" class="col mr-3 btn btn-light btn-rounded" data-mdb-ripple-color="dark">Copy</button> </div> </center> As I am trying to convert my url to short url, I also tried using python function to also create a short link. Below is how the pyshorteners function module is working. import pyshorteners link = input("Enter the link:") Enter the link:>? http://127.0.0.1:8000/affiliation/link/10003/ shortener = pyshorteners.Shortener() x = shortener.tinyurl.short(link) print(x) h__ps://tinyurlcom/yfzx7uxm #this is the short link i have received and its working. #Also … -
Connect local database in heroko using django
I want don't want to use the Heroku database instead I want to use my local database in the Heroku server. so how do I connect my local database to Heroko. -
Can't I save data in django model from files other than views?I am getting this error
I want to save data in a model. Lets say I want to hard code data from views.py it saves but when i try to do it by creating a seperate file it doesn't. It doesnt import models at all giving error ImportError: attempted relative import with no known parent package.Am I missing something here : I have tried doing: from .models import className from models import className from . import models and calling models.className -
Unable to show user specific link to specific page in django
I would like to create user specific links. I mean, when user signed up and logged in, he has redirected to create/ page. In that page user fills out the form and after pressing button, user has to redirect to list/ page, where there are user specific links to specific page, which contain schedule. Schedul appered from data, which user provided in create/ form. So my problem is, when I filled out the form and redirect to list/ page, there are no links. My code: models.py from django.db import models from django.contrib.auth.models import User class File(models.Model): file = models.OneToOneField(User, on_delete=models.CASCADE, null=True) #Further, they are fileds, which is nececary to create schedule. #title = models.CharField('Название Графика', max_length = 50) #x_title = models.CharField('Название Оси Х', max_length = 50) #y_title = models.CharField('Название Оси Y', max_length = 50) #etc... views.py: def create(request): error = '' if request.method == 'POST': form = FileForm(request.POST) if form.is_valid(): form.save() return redirect('grafic:list') else: error = 'Форма была неверной(' form = FileForm() data = { 'form': form, 'error': error, } return render(request, 'graf/create.html', data) def list(request): qs = File.objects.filter(file=request.user) context = { 'user': request.user, 'qs': qs, } return render(request, 'graf/list.html', context) list.html {% extends 'base.html' %} {% block content %} … -
count event by day?
I need to do a count view that counts the appointments by day for example if there are 4 appointments on June 20 and 3 appointments on June 21. if I logged in on June 20 it will only show me the 4 appointments. this is my current view which didn't work models.py class Appointment(models.Model): appointment_date = models.DateField(null=True) appointment_time = models.TimeField(null=True) patient = models.ForeignKey('Patient', on_delete=models.CASCADE) reseptionist = models.ForeignKey('Reseptionist', on_delete=models.SET_NULL, blank=True, null=True) service = models.ForeignKey('Service', on_delete=models.CASCADE) physician = models.ForeignKey('Physician', on_delete=models.CASCADE) views.py def count_appointment(request): appointment = Appointment.objects.filter(appointment_date__day=datetime.today().day).count() data = {} data['appointment'] = appointment return render(request, 'index.html', context=data) index.html {{appointment.count}} -
How to logout in django
i have created login system for my project. but this login is not django's built in authentication. I think i have successfully completed login but i am unable to logout by either built-in authentication or custom logout. def loginpage(request): if request.method == "POST": loginemail = request.POST.get('email') loginpassword = request.POST.get('password') try: var = Patient.objects.get(email=loginemail) if var.password == loginpassword: #i am not sure for this line also wheather it's right or not for login request.session['user'] = var.id return redirect('/patient') else: messages.add_message(request, messages.INFO, 'Hello world.') except: return HttpResponse("Not Logged in") return render(request, 'home/login.html') this is function i have created for login but not sure if that is working perfectly or not but if i print(request.session) it is giving <django.contrib.sessions.backends.db.SessionStore object at 0x10a150bb0> def handlelogout(request): if request.session: print(request.session) try: del request.session['user'] except: print("not logged out") return redirect('loginpage') this is function for log out. but it always print not logged out in terminal. now what can i do to specify login and logout in this project. -
django-autocomplete-light dependant filter over 3 models
I have 3 models. class FilterDefaultValues(BaseModel): value = models.CharField(max_length=255, null=True, blank=True) display_value = models.CharField(max_length=255, null=True, blank=True) class Filter(BaseModel): name = models.CharField(max_length=255) default_value = models.ManyToManyField(FilterDefaultValues, blank=True) class ProductFilter(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='filters') filter = models.ForeignKey(Filter, on_delete=models.CASCADE) value = models.ForeignKey(FilterDefaultValues, blank=True, on_delete=models.RESTRICT) urls.py class LinkedDataView(autocomplete.Select2QuerySetView): def get_queryset(self): qs = super(LinkedDataView, self).get_queryset() filter = self.forwarded.get('filter', None) if filter: qs = qs.filter(filter_id=filter) return qs urlpatterns = [ url( '^linked_data/$', LinkedDataView.as_view(model=ProductFilter), name='linked_data' ), ] forms.py class ProductFilterForm(forms.ModelForm): def clean_test(self): filter = self.cleaned_data.get('filter', None) value = self.cleaned_data.get('value', None) if value and filter and value.filter != filter: raise forms.ValidationError('Wrong owner for test') return value class Meta: model = ProductFilter fields = ('product', 'filter', 'value', 'value_type', 'product_images', 'is_variation') widgets = { 'value': autocomplete.ModelSelect2(url='linked_data', forward=('filter',)) } class Media: js = ( 'linked_data.js', ) What I want to is in the admin panel when the user selects a filter, then the value field must be populated with appropriate default values. But now what I get is: When user selects filter then only productfilter items are populated here. What I am missing here? -
Why Django cannot extends my form.html contact page and returns a TemplateSyntaxError or an Exception Thrown?
I'm trying to build a contact page ("/contact-us/") as a modular app instead of the similar already working contact page ("/contact/") located in the "/app/" directory. The former is failing, returning either Exception Thrown or TemplateSyntaxError while trying to {% extends %} the form.html with its base.html. My file structure: BlogDjango |-BlogDjango | | settings.py | | urls.py |-app | |-Templates | | | base.html | | | form.html |-blogpost |-contactform | |-Templates | | | base.html | | | form.html | | forms.py | | views.py settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),os.path.join(BASE_DIR,'app','templates'),os.path.join(BASE_DIR,'contactform','templates')],... base.html <!DOCTYPE html> <html> <head></head> <body> {% block content %}{% endblock %} </body></html> form.html {% extends base.html %} {% block content %} {% if title %} <h1>{{ title }}</h1> {% endif %} <form method='POST' action='.'> {% csrf_token %} {{ form.as_p }} <button type='submit'>Send</button> </form> {% endblock %} It seems that Django doesn't recognise that the base.html is located in the same directory than the form.html and therefor cannot extend it. So I get those two errors thrown at me: Exception Thrown: Failed lookup for key [base] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x000001D62DDBBAF0>>, 'request': <WSGIRequest: GET '/contact-us/'>, … -
Does HTTP 401 response from server clears user credentials from browsers cache?
My Django 2.2 application is using basic http authentication with Apache LDAP. Users can login by entering their username and password using the browser pop-up (image shown below): I'm working on writing a logout function that would return a httpresponse. Below is an incomplete example snippet of what I have mentioned: def process_request(self, request): if request.path == '/accounts/logout/': httpResponse = HttpResponse() httpResponse.status_code = 401 httpResponse.headers['WWW-Authenticate'] = 'Basic realm="<same realm as in the http server>"' return httpResponse else: ... I wanted to know if returning Status code: 401, clear the credentials in browser cache. If not, then is there any other way I can achieve this? Any help is highly appreciated! -
Python: Module not found while importing from multiple subfolders
I have a folder structure like below (attached image) enter image description here In Main.py I imported all the folders. Now Main.py calls subMain.py which is inside the Project 1. subMain.py imports spark, common etc. Now sparkUtils.py has functions from helper.py hence need to import helper.py This throws module import error that "No module named Common" I tried putting init.py in all the folders, however no luck. Can anyone help please? Thanks in advance. -
How to recover deleted data from AWS PostgreSQL database for Django project?
I tried to add a new field in my existing Django project. I run the following command to do it: manage.py makemigrations manage.py migrate appname zero manage.py makemigration manage.py migrate Now I have lost all my previous data from the database (PostgreSQL) for that application. The migration folder only has the most recent migration file. How can I retrieve previous data? I am using AWS PostgreSQL in the project. Any help/suggestion will be appreciated. -
How to include the thumbnail image with using TabularInline admin model?
What I am trying to do I would like to include thumbnail in PhotoInline and could be shown into ProductAdmin. What I have done I made two admin model which are ProductAdmin and PhotoInline. PhotoInline model is a separate admin model that only contains information of photos of products, which is to be connected to ProductAdmin. Inside of PhotoInline, I included custom admin function called product_thumbnail and tried to include list_display admin option of ProductAdmin. Here are my codes: class PhotoInline(admin.TabularInline): ''' PhotoAdmin Definition ''' model = models.Photo fieldsets = ( ( None, { 'fields': ('caption', 'file',) } ), ) extra = 0 and then ProductAdmin admin model looks as follows: @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): ''' ProductAdmin Definition ''' inlines = [ PhotoInline, ] list_display = ( 'product_name', 'product_price', 'product_color', 'product_size', 'product_category', 'is_onsale', 'is_newarrival', 'is_preorder', ) list_filter = ( 'is_onsale', 'is_newarrival', 'is_preorder', ) ordering = ('product_name', 'product_price', 'product_category') search_fields = [ 'product_name', 'product_category' ] Error that I got <class 'products.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[8]' refers to 'product_thumbnail', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'products.Product'. It seems my approach is somewhat wrong. Do I need to include separate ImageField for my Product … -
Django: Simple One:Many fields aren't showing in parent object view in admin
I'm new to Django and have made a couple of classes whereby one Account can have many Subscribers. When viewing a subscriber in the django admin, it correctly shows which account the subscriber is related to. However, when looking at the account, it does not show which subscribers it has. I saw an article (How to create many-to-one relation with django and to display it in admin interface) that suggested using inlines, although it’s not working for me. Where am I going wrong here? Models.py: from django.db import models from django.contrib.auth.models import AbstractUser class Account(AbstractUser): pass 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) date_joined = models.DateTimeField(auto_now_add=True, null=True) verified = models.BooleanField(default=False) account = models.ForeignKey( Account, on_delete=models.CASCADE) def __str__(self): return self.email list_display = ('first_name', 'email', 'date_joined', 'verified') Admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from accounts import models # does nothing class SubscriberInline(admin.TabularInline): model = models.Subscriber extra = 1 admin.site.register(models.Account, UserAdmin) # does noting class AccountAdmin(admin.ModelAdmin): inlines = [SubscriberInline, ] #inlines = (SubscriberInline, ) @admin.register(models.Subscriber) class SubscriberAdmin(admin.ModelAdmin): list_display = ("first_name", "email", "date_joined", "verified", "account") -
Remove specific object from Many-to-many relationship
I have Two models : class Product(models.Model): product_model = models.CharField(max_length=255, default='') ... class Discount(models.Model): name = models.CharField(max_length=255, default='') items = models.ManyToManyField(Product, blank=True) discount_percent = models.IntegerField(default=0, validators=[ MaxValueValidator(100), MinValueValidator(1), ] ) I want to delete specific item from items(ManyToManyField) my views : def delete_from_discount(request, id, product_url): if request.user.is_staff or request.user.is_superuser: a = Product(product_url=product_url) b = Discount(id=id) b = b.items.remove(a) return redirect("/staff/discount/"+id) else: return redirect('/staff') There is no error but also nothing change from my models, no remove my html: {% for dis in discount.items.all %} <a href="/staff/discount/delete-from-discount/{{discount.id}}/{{dis.product_url}}/">delet</a> {% endfor %}