Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error while binding html with mysql database using django
from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages #from django.http import HttpResponse def Insertrecord(request): if request.method=='POST': if request.POST.get('epname')and request.POST.get('email')and request.POST.get('country'): saverecord=EmpInsert() saverecord.empname=request.POST.get('empname') saverecord.email=request.POST.get('email') saverecord.country=request.POST.get('country') saverecord.save() message.success(request,'Record Saved Successfully...!') return render(request,'Index.html') else: return render(request,'Index.html') [views.py file][1] when binding HTML form with MySQL database by django after submiting submit button from html form I get error ValueError at / The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead. Request Method: POST -
raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use child_tag.set() instead
when i am tring to send post request to add blog-post in my database. i am getting this error. raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use child_tag.set() instead. i want to create blog-post with minimum data like title. i want to save blog-post with at least title so that i can edit later. here is my post request img my model class Post(models.Model): title = models.CharField(max_length=200, unique=False) slug = models.SlugField(max_length=300, unique=True, null=True, blank=True) author = models.ForeignKey("users.NewUser", on_delete= models.CASCADE) tag = models.ForeignKey(MainTag,to_field='tag_name', blank=True, null=True, on_delete=models.SET_NULL) child_tag = models.ManyToManyField(ChildTag, blank=True, null=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) + "-" + str(self.id) super(Post, self).save(*args, **kwargs) self.slug = slugify(self.title) + "-" + str(self.id) super(Post, self).save(*args, **kwargs) my post request class BlogpageView(APIView): def post(self, request, *args, **kwargs): new_data = request.data.copy() new_data.update({'author':request.user.id}) serializer = PostSerializer(data=new_data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST ) serializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' def create(self, validated_data): return Post.objects.create(**validated_data) def validate(self, data): if hasattr(self, 'initial_data'): unknown_keys = set(self.initial_data.keys()) - set(self.fields.keys()) if unknown_keys: raise ValidationError("Got unknown fields: {}".format(unknown_keys)) return data -
How it is filtering unique fields of email?
Whats is the difference between email and self.email def is_exists(self): if SignUp.objects.filter(email=self.email): return True return False``` -
Browse files from django template page
is there any way how to browse files in specific local folder with django template. I made an application that backup routers configuration every 3 days ans save these backuped configuration files into django server. I want to let users to browse these file in case they need to go back to old config file. files now are stored into ROOT/config_backup directory I want users to be able to browse only from that folder -
Django + JavaScript(jQuery) dynamic removal of dropdown option?
I am working on a backend Django project which uses a Bootstrap selectpicker. I am working on an edit view, and having trouble removing certain dropdown select options, based on the users previous saved information. I have tried using jQuerys .remove() .hide() and plenty other options but all select options still show. The dropdown provides a list using a django context proocessor <div class="form-group"> <label>Job Type</label> <div class="select-panel"> <select class="selectpicker" name="job_type" id="edit_job_type"> <option value="">Select</option> {% for obj in job_type %} <option value="{{ obj.name }}" second_job_cat="{{ obj.second_job_cat }}">{{ obj.name }}</option> {% endfor %} </select> </div> </div> And then in the JS popup modal GET request, that provides the popup modal form with the users existing data. // grab from the django view the users previous job type. let select_job_type = data['edit_job_type']; // set the value to previous value $("#edit_job_type").selectpicker('val', select_job_type); $("#edit_job_type").selectpicker('refresh'); This is the function I am trying to use to remove the values I do not want. let second_job_cat = document.getElementById('edit_job_type'[sel].dataset.secondJobCat; $("#edit_job_type > option").each(function() { if (second_job_cat !== this.dataset.secondJobCat){ console.log($(this).val()) $(this).remove() // also tried $(this).val().remove() } }); When I console.log the $(this).val() it does log all of the option values I do not want, which should be a good sign? … -
Database querying
I'm having an issue here that I want clarification with, see, I'm making a program that does analysis of data. I wanted to query data from different users, the data is numerical by the way, whenever I'd get subject marks from a user, I want the system to return the name of the user who has those marks. It was all working fine until I tried querying the users with the same marks, and all I could get was an error analyzer.models.ResultsALevel.MultipleObjectsReturned: get() returned more than one ResultsALevel -- it returned 4! So I was trying to find a way to still query and return the name of users with that subject mark, even if they have the same marks. I believe that should be possible since the users have different id's and stuff, help would be much appreciated! Here's my views.py biology_marks = [] for student in ResultsALevel.objects.all(): biology_marks.append(student.advanced_biology_1) value_1_biology = ResultsALevel.objects.get(advanced_biology_1=biology_marks[-1]).student_name.last_name value_2_biology = ResultsALevel.objects.get(advanced_biology_1=biology_marks[-2]).student_name.last_name value_3_biology = ResultsALevel.objects.get(advanced_biology_1=biology_marks[-3]).student_name.last_name value_4_biology = ResultsALevel.objects.get(advanced_biology_1=biology_marks[-4]).student_name.last_name -
Avoid invocation of a business logic by looking up a table column value without race-condtion
Is the possible to to effectively block invocation of a function by looking a database table column value. I've a model(LookupTable) as follows, In my app(Django + Postgres) There is a chance that 'my_function' is called in two ways 1. by a third party(via API call) after a particular event happened and 2. by my own job ( call after some fixed time after particular event happened) I want to make sure 'my_function' is called either by third party or by my own job for a 'unique_id'. My plan is to look the 'LookupTable' status column and to determine whether to continue the execution of 'my_function'. Once any of the process invoked the function mark the status from 'I' to 'U'. I use the following strategy to make sure, if both the process start work at the same time LookupTable(models.Model): some_unique_id = models.CharField(max_length=256) status = models.CharField(choices=(('I', 'Initiated'), ('U', 'Updated'))) @transaction.atomic def my_function(unique_id): # The following call is invoked only if status is 'Initiated'. lookup = LookupTable.objects.select_for_update.filter(some_unique_id=unique_id, status='I'). # only one record per unique_id if not lookup: return lookup.update(state='U') # My business logic which create/update some records in some other table ---------- ---------- I've used 'select_for_update' and transaction to block other … -
Django and Bootstrap: prevent warning box from appearing if there is an empty string
I'm using Django templates and Bootstrap to render a red alert box if there is a message. The code is: views.py else: return render(request, 'auctions/listing.html', { 'listing': listing, 'form': BidForm(), 'message': '', 'comments': listing.comments.all() }) listing.html <div> <p>Starting Bid: {{ listing.starting_bid}}</p> <p>Current Bid: {{ listing.price }}</p> <div class="alert alert-danger" role="alert" style="display: inline-block;"> {{ message }} </div> </div> The red warning box renders if there is no message (i.e. an empty string), which seems sensible and intuitive. However, when I remove message from views.py altogether, the red warning box still renders. else: return render(request, 'auctions/listing.html', { 'listing': listing, 'form': BidForm(), # 'message': '', 'comments': listing.comments.all() }) What am I doing wrong here? Thanks! -
authenticate had None value
In form to I try login user but I have message like below 'AnonymousUser' object has no attribute '_meta' In view sign_in my user had also None value, my username and password is correct I am sure.Where is a problem? In view sign_in my user had also None value, my username and password is correct I am sure.Where is a problem? forms from django import forms from django.contrib.auth.models import User from django.core.validators import MinLengthValidator from django.utils.translation import gettext_lazy as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field, Column from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions class UserSignUpForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserSignUpForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], label="", required=True, widget=forms.RadioSelect( attrs={'style':'max-width: 20em; ', 'autocomplete':'off', }) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", validators=[MinLengthValidator(8, message="Minimum 8 characters"), ], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) class Meta: model = User fields = ('who', "username", 'first_name', 'last_name', "password", ) help_texts = {"username": None} widgets = { 'username': forms.TextInput(attrs={}), 'first_name': forms.TextInput(attrs={}), 'last_name': forms.TextInput(attrs={}), } def clean(self): cleaned_data = super(UserSignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: msg = _(f'Password and confirm … -
Error loading psycopg2 module in aws with django
I am trying to put my django's webpage to AWS. However, I receive a problem. It says to me that It can't find psycopg2 library. Jul 9 17:09:09 ip-172-31-44-212 web: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) Jul 9 17:09:09 ip-172-31-44-212 web: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' Using pip list I can see what things are instaled in my virtual env. And it's clear that I have installed psycopg2. (eb-virt) PS C:\Users\ANDRES\Desktop\GlobalcodigoTfg\project> pip list Package Version ---------------------- --------- APScheduler 3.7.0 asgiref 3.3.4 astroid 2.5.6 attrs 20.3.0 Automat 20.2.0 aws-psycopg2 1.2.1 backcall 0.2.0 beautifulsoup4 4.9.3 certifi 2020.12.5 cffi 1.14.5 chardet 4.0.0 click 7.1.2 colorama 0.4.4 constantly 15.1.0 cryptography 3.4.6 cssselect 1.1.0 cycler 0.10.0 decorator 4.4.2 dj-database-url 0.5.0 dj-places 4.0.0 Django 3.2.3 django-apscheduler 0.5.2 django-decouple 2.1 django-durationwidget 1.0.5 django-extensions 3.1.3 django-location-field 2.1.0 docopt 0.6.2 future 0.18.2 geocoder 1.38.1 geographiclib 1.52 geonames 0.1.3 geopy 2.1.0 googlemaps 4.4.5 graphviz 0.16 gunicorn 20.1.0 humanfriendly 9.1 hyperlink 21.0.0 idna 2.10 incremental 21.3.0 ipykernel 5.5.5 ipython 7.24.1 ipython-genutils 0.2.0 isort 5.7.0 itemadapter 0.2.0 itemloaders 1.0.4 jedi 0.18.0 jmespath 0.10.0 jupyter-client 6.1.12 jupyter-core 4.7.1 kiwisolver 1.3.1 lazy-object-proxy 1.5.2 llvmlite 0.36.0 lxml 4.6.2 Mako 1.1.4 MarkupSafe 2.0.1 matplotlib 3.4.2 matplotlib-inline 0.1.2 mccabe 0.6.1 mysql-connector-python … -
Unexpexted atribute error 'UserProfileView' object has no attribute 'get'
I tried so hard to fix issues but I keep getting a issue after issue I hope someone can help me. Traceback: AttributeError at /profile_page/post.profile 'UserProfileView' object has no attribute 'get' models.py: class UserProfileView(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to='images/profile/') website_url = models.CharField(max_length=255, null=True, blank=True) facebook_url = models.CharField(max_length=255, null=True, blank=True) pinterest_utl = models.CharField(max_length=255, null=True, blank=True) instagram_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('article-detail', args=[str(self.id)]) home.html: <a href="{% url 'profile_page' pk %}"> urls.py: path('profile_page/<str:pk>', UserProfileView, name='profile_page'), -
Deleting posts via Django command doesn't work
Deleting posts via Django command does not work. I do not know what to do, I am at a dead end. I hope you can help me... delnc.py File command class Command(BaseCommand): help = 'Командa для удаления всех постов из категории' requires_migrations_checks = True missing_args_message = 'Недостаточно аргументов' def add_arguments(self, parser): parser.add_argument('category_name', type=str) def handle(self, *args, **options): print('Мастер код: 7548') answer = input('Введите Мастер код для удаления: ') if answer == '7548': try: category = str(options['category_name']) Post.objects.filter(postCategory__category_name=category).delete() Post.save() self.stdout.write(self.style.SUCCESS(f'Успешно. Все новости категории {category} удалены!')) except Post.DoesNotExist: self.stdout.write(self.style.ERROR('Нет такой категории! Отказано!')) else: self.stdout.write(self.style.ERROR('В доступе отказано!')) models.py class Category(models.Model): category_name = models.CharField(max_length=64, unique=True) subscribers = models.ManyToManyField(User, blank=True, null=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.category_name class Post(models.Model): PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='Автор поста') PostNews = 'PN' PostArticle = 'PA' # «статья» или «новость» POSITIONS = [ (PostArticle, 'Статья'), (PostNews, 'Новость'), ] postCategory = models.ManyToManyField(Category, verbose_name='Категория поста', through='PostCategory') title = models.CharField(max_length=50, verbose_name='Название') positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle, verbose_name='Тип поста') category_id = models.ForeignKey(Category, verbose_name='Категория', null=True, on_delete=models.CASCADE, related_name='category_id') data = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') data_update = models.DateTimeField(auto_now=True, verbose_name='Дата редактирования') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото', blank=True, default='/photos/def/1.jpg/') previewName = models.CharField(max_length=128, verbose_name='Превью поста') text = models.TextField(verbose_name='Текст поста') rating = models.SmallIntegerField(default=0, verbose_name='Рейтинг') public = models.BooleanField(default=True, … -
how to partially display information from django database?
I want to partially display information from django database. For example: There is a phone number in the database - +33547895132. In html i want to display - +3354*****2 -
In my blogging website i want to delete a user and all its associated blogs and comments
I deletes a user then all the associated blogs were also deleted but the associated comments are not deleted why comments model is indirectly related to User model using foreign key. Can anyone give me the answer models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class blogpost(models.Model): created_by=models.ForeignKey(User,on_delete=models.CASCADE) topic=models.CharField(max_length=122,null=True,blank=False) title=models.CharField(max_length=250,blank=False) post=models.TextField() likes=models.ManyToManyField(User, related_name='blog_posts') date=models.DateTimeField(auto_now_add=True ) def __str__(self): return ' (' +str(self.created_by)+') Title- '+self.title class Meta: ordering=['-date'] class CommentModel(models.Model): post = models.ForeignKey(blogpost ,related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length = 100) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' %(self.post.title, self.name) class Meta: ordering=['-date_added'] views.py def comment_view(request, pk): if request.method=='POST' and 'comment_button' in request.POST: body=request.POST.get('comment_text') post=blogpost.objects.get(pk=pk) obj=CommentModel(body=body) obj.name=request.user obj.post=post obj.save() return HttpResponseRedirect(reverse('detaildata',args=[str(pk)])) -
Django user registration through mobile number
I am recently started to learn django and REST API development. Currently I am trying to create a user signup system where user's mobile number will be unique and user will login further using registered mobile number and an OTP. can anybody please guide through the process -
Django channels "Temporary failure in name resolution", and I'm not sure what to do about it
I'm loosely following a tutorial on YouTube, trying to get a basic understanding of implementing channels, and I am having difficulty figuring out this error: django | WebSocket HANDSHAKING /ws/events/ [172.19.0.1:49272] django | INFO 2021-07-10 12:57:11,000 runserver 11 140153597114112 WebSocket HANDSHAKING /ws/events/ [172.19.0.1:49272] django | ERROR 2021-07-10 12:57:12,139 server 11 140153597114112 Exception inside application: [Errno -3] Temporary failure in name resolution django | Traceback (most recent call last): django | File "/usr/local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ django | return await self.application(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ django | return await application(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__ django | return await self.inner(dict(scope, cookies=cookies), receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/sessions.py", line 254, in __call__ django | return await self.inner(wrapper.scope, receive, wrapper.send) django | File "/usr/local/lib/python3.9/site-packages/channels/auth.py", line 181, in __call__ django | return await super().__call__(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__ django | return await self.inner(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 150, in __call__ django | return await application( django | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 94, in app django | return await consumer(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 58, in __call__ django | await await_many_dispatch( django … -
Django-atom or Atom-django autocomplete not working after installation
I also had the same problem while trying to use the django-atom autocomplete snippet and after reading different articles on it here is how I go about it. Go to the directory of the installed autocomplete package, in this case here: C:\Users\user.atom\packages\django-atom Go to the snippet folder and you'll find a .cson file, right click and open it with an editor in this case here is the directory: C:\Users\user.atom\packages\django-atom\snippets Copy everything inside the file and go back to the snippets.cson file in .atom parent directory, in this case here: C:\Users\user.atom Right click and open the snippets file with an editor, scroll down and paste everything you copied earlier into the file then save. Bro, now you can enjoy your beautiful snippets. -
Looping through two queryset in django template
I have 3 models, class Candidate(models.Model): full_name = models.CharField(max_length=255) class CandidateProjects(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name="projects") project_name = models.CharField(max_length=255) class CandidateTools(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name="tools") tool_name = models.CharField(max_length=255) In template, i have the object of Candidate. I want to show Tools and Projects data in a tabular format, like: Can anyone suggest how can i access both models in template only. Thanks.. -
Collect data such as IP and browser agent in Django, HTML form and jQuery
This is how I have defined my Contact form of my website (ignore php-email-form class please): <form action="" id="contactForm" method="post" role="form" class="php-email-form"> {% csrf_token %} <div class="row"> <div class="col-md-6 form-group"> <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" required> </div> <div class="col-md-6 form-group mt-3 mt-md-0"> <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" required> </div> </div> <div class="form-group mt-3"> <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required> </div> <div class="form-group mt-3"> <textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea> </div> <div class="my-3"> <div id="loading" class="loading">Please wait...</div> <div class="error-message"></div> <div id="sent-message" class="sent-message">Your message has been sent. Thank you!</div> </div> <div class="text-center"><button type="submit">Send Message</button></div> </form> And this is how I'm intercepting the form: $('#contactForm').submit(function(e){ e.preventDefault() $('#loading').css("display", "block") $.ajax({ type : "POST", url : "/contact/", data: { sender_name : $('#name').val(), sender_email : $('#email').val(), message_subject : $('#subject').val(), message_text : $('#message').val(), csrfmiddlewaretoken : csrftoken, datatype : "json", }, success: function(){ $('#loading').css("display", "none"), $('#sent-message').css("display", "block"), $('#contactForm')[0].reset() }, }); }); And this is now I'm processing the form: def contact(request): if request.is_ajax(): sender_name = request.POST.get('sender_name') sender_email = request.POST.get('sender_email') message_subject = request.POST.get('message_subject') message_text = request.POST.get('message_text') email_subject = f'Contact Form: {message_subject}' email_from = f'{sender_name} <{sender_email}>' email_to = ['me@gmail.com', ] html_message = f'Name: {sender_name}<br>Email: {sender_email}<p>{message_text}' send_mail(email_subject, '', email_from, email_to, html_message=html_message) response = {} return … -
got an unexpected keyword argument error eventhough it has been described
This might be an silly error but have tried a lot of was but it was not able to be solved. Hope someone can help. Traceback: TypeError at /profile_page/pro UserProfileView() got an unexpected keyword argument 'pro' views.py: class UserProfileView(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to='images/profile/') website_url = models.CharField(max_length=255, null=True, blank=True) facebook_url = models.CharField(max_length=255, null=True, blank=True) pinterest_utl = models.CharField(max_length=255, null=True, blank=True) instagram_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, blank=True) def get_absolute_url(self): return reverse('name-of-some-view', kwargs={'pk': self.pk}) def __str__(self): return str(self.user) urls.py: path('profile_page/<str:pro>', UserProfileView, name='profile_page'), -
HTTP_REFERER not in request.META, how to set it?
I am trying to fix csrf protection for my Django views. The CsrfViewMiddleware checks if there is the referer as follows: referer = request.META.get('HTTP_REFERER') if referer is None: return self._reject(request, REASON_NO_REFERER) I am trying to set the 'HTTP_REFERER' in the headers as such: const config = { headers : { "Referer": "https://example.com/", "HTTP_REFERER": "https://example.com/", "Referrer-Policy": "strict-origin-when-cross-origin" } } const fetcherGraphql = (query) => request(serverURl + "/graphql", query, config); Django fails with REASON_NO_REFERER because there is no HTTP_REFERER in the request.META How do I get it in there? Or am I missing something else? -
Server Error (500) in deployment of django project to heroku
Server error 500 on Django when deployed on Heroku when debug is set to False I am using django 3.1.6 -
Printing hello world on the django server using vscode
I am a newbie in django I have been trying to print hello world on the django server and its not responding. I have set the url.py on both the app and project file Set the views.py Still not gotten hello world on the django server. I will appreciate any help -
Recieving Server Error (500) when deploying Django app to Heroku
I've been struggling for days just trying to deploy my site to Heroku. I've referenced many other Stack Overflow questions about this topic, such as: Django Heroku Server Error (500) when I set Debug - False on True it is working fine Heroku/Django deploy: why am I getting an error 500 with successful deploy and static collection? For reference, I was following Heroku's guide on the deployment of Django apps when doing this. Below is the relevant code to this dilemma of mine. base_settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = thekey # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['dazzling-kobuk-valley-23546.herokuapp.com','localhost','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store.apps.StoreConfig', 'basket.apps.BasketConfig', 'account.apps.AccountConfig', 'orders.apps.OrdersConfig', 'checkout.apps.CheckoutConfig', 'mptt', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] WSGI_APPLICATION = 'hifive.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Static files … -
How to override get_queryset() of ModelAdmin?
I want to override a ModelAdmin to limit some users. The superadmins have all the rights but the others have restricted rights. They can't see/add/modify/delete all objects but only some. Also, the objects they can modify contain a many_to_many field and I want to limit the choices in the list. For this, I overloaded several methods, but I have a problem when I overload get_queryset(). Indeed, it reduces the list of objects, which is perfect in my case but when I click on an object to modify it, I have the following error: MultipleObjectsReturned at /fr/admin/commission/article/26/change/ get() returned more than one Article -- it returned 2! Request Method: GET Request URL: http://127.0.0.1:8000/fr/admin/commission/article/26/change/?_changelist_filters=q%3D Django Version: 2.2.24 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Article -- it returned 2! Exception Location: /home/aurelien/dev/extranet_thourotte/venv/lib/python3.9/site-packages/django/db/models/query.py in get, line 410 Python Executable: /home/aurelien/dev/extranet_thourotte/venv/bin/python3 Python Version: 3.9.5 my ModelAdmin: @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): """ ArticleAdmin to save automaticaly the author """ list_display = ('titre', 'auteur', 'date', 'date_update') list_filter = ('rubriques', 'auteur',) search_fields = ('titre',) exclude = ('auteur',) def get_queryset(self, request): queryset = super().get_queryset(request) if not request.user.is_superuser: rubriques = Rubrique.objects.filter(admins=request.user) queryset = queryset.filter(rubriques__in=rubriques) return queryset def formfield_for_manytomany(self, db_field, request, **kwargs): if not request.user.is_superuser and db_field.name == …