Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0 TestCase unexpected creation of Model objects for every test
I have some tests and I need one Board object which I created with Board.objects.create() to have one Object with the primary key 1. But i have figured out, that there are a new object for every test, so i there I have for example 'pk': 5. If i add more tests the 'pk': 5 could be wrong, because it change to 'pk': 6. How is it possible to create only one Board object with 'pk': 1 for all tests? I am using Django 2.0.3 from django.test import TestCase from django.urls import reverse, resolve from .views import home, board_topics, new_topic from .models import Board class BoardTopicsTests(TestCase): def setUp(self): Board.objects.create(name='Django', description='Django board.') def test_board_topics_view_success_status_code(self): url = reverse('boards:board_topics', kwargs={'pk': 5}) response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_board_topics_view_not_found_status_code(self): url = reverse('boards:board_topics', kwargs={'pk': 99}) response = self.client.get(url) self.assertEquals(response.status_code, 404) def test_board_topics_url_resolves_board_topics_view(self): view = resolve('/boards/1/') self.assertEquals(view.func, board_topics) def test_board_topics_view_link_back_to_homepage(self): board_topics_url = reverse('boards:board_topics', kwargs={'pk': 3}) response = self.client.get(board_topics_url) homepage_url = reverse('boards:home') self.assertContains(response, 'href="{0}"'.format(homepage_url)) def test_board_topics_view_contains_navigation_links(self): board_topics_url = reverse('boards:board_topics', kwargs={'pk': 2}) homepage_url = reverse('boards:home') new_topic_url = reverse('boards:new_topic', kwargs={'pk': 2}) response = self.client.get(board_topics_url) self.assertContains(response, 'href="{0}"'.format(homepage_url)) self.assertContains(response, 'href="{0}"'.format(new_topic_url)) -
Error : 'User' object has no attribute 'get' when trying to access current user in ModelForms for a ModelChoiceField dropdown
So below is the views.py and I'm trying to load a view with modelform. And within the modelform I need to load modelchoicefield depending on the current user logged in and tried the below solution(check forms.py.) When I run it, i get Attribute Error :object has no attribute 'get' Help is highly appreciated, there's nothing in stackoverflow. views.py: class HomeView(View): def get(self, request, *args, **kwargs): form=PreDataForm(request.user) return render(request, 'mainlist.html', { "form":form, }) models.py: class PreData(models.Model): journalname = models.CharField(max_length=400, blank=False, null=True, default='') forms.py: class PreDataForm(forms.ModelForm): class Meta: model=PreData fields=['journalname'] def __init__(self,user, *args, **kwargs): super(PreDataForm, self).__init__(user, *args, **kwargs) self.fields["journalname"].queryset = Journals.objects.filter(journalusername=user) html file: {% extends 'home-base.html' %} {% load crispy_forms_tags %} {% block title %} Welcome to Metrics - JSM {% endblock %} {% block content %} <div class="col-md-9 col-centered" > <div class="backeffect" > {% if data %} {% else %} <b>Seems you are first time around here, Why not <b>{% include 'modal_first_stage.html' %}</b> to get started? :)</b> {% endif %} {% endblock %} -
How to find serializer for a django model?
I am working on a project in which I am using django-polymorphic for retrieving polymorphic result sets. I have some models which inherit from a parent model. For example, Model B inherits from Model A and Model C also inherits from Model A. Model B and Model C have their own serializers and when I query all records for model A, I get a mixed resultset containing instance of Model B and C. How can I dynamically select serializer based on the instance? Thanks -
Postgres complains about non-existant constraint
I am in the progress of migrating our database schema in postgresql and i get this error in Django(1.11.11): django.db.utils.ProgrammingError: constraint "djstripe_charge_account_id_597fef70_fk_djstripe_account_id" for relation "djstripe_charge" already exists However executing ALTER TABLE djstripe_charge DROP CONSTRAINT djstripe_charge_account_id_597fef70_fk_djstripe_account_id ; in psql gives the following error: ERROR: constraint "djstripe_charge_account_id_597fef70_fk_djstripe_account_id" of relation "djstripe_charge" does not exist I verified in psql with \d djstripe_charge and it doesn't show up on the relations list In django, the error occurs(90% sure) in the migration code: migrations.AddField( model_name='charge', name='account', field=models.ForeignKey(help_text='The account the charge was made on behalf of. Null here indicates that this value was never set.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='charges', to='djstripe.Account'), ), Why does dhango complain about this? -
How to add css to the default form elements in django
I am making an app which has login page. I am using default django username and password fields.I want to add some css to it.How can we modify the default style and make it look good My HTML is of this form <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Purple Admin</title> <link rel="stylesheet" href="{% static 'css/materialdesignicons.min.css' %}"> <!-- plugins:css --> <link rel="stylesheet" href="{% static 'css/perfect-scrollbar.min.css' %}"> <!-- endinject --> <!-- plugin css for this page --> <link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}"> <!-- End plugin css for this page --> <!-- inject:css --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- endinject --> <link rel="shortcut icon" href="{% static 'images/favicon.png' %}"> </head> <body> <div class="container-scroller"> <div class="container-fluid page-body-wrapper"> <div class="row"> <div class="content-wrapper full-page-wrapper d-flex align-items-center auth-pages"> <div class="card col-lg-4 mx-auto"> <div class="card-body px-5 py-5"> <h3 class="card-title text-left mb-3">Login</h3> <form method="post" action="{% url 'login' %}"> <div class="form-group"> <label>Username: </label> {{ form.username }} </div> <div class="form-group"> <label>Password: </label> {{ form.password }} </div> <div> {% if form.errors %} <font color="red">Your username and/or password didn't match. Please try again.</font> {% endif %} </div> <div class="form-group d-flex align-items-center justify-content-between"> <a href="#" class="forgot-pass">Forgot password</a> … -
A web app for users to easily create banners for my website (Python, Django/Flask)
I have a need to build a new tool to help me with my job and I wonder if anyone here can give me any advice. I want to build a simple website using Flask and Python (no issues there) that lets users create one of four types of banner for our website. The process would be something like: A. User goes to website url B. User enters the following information: Booking reference number (essential) Type of banner (drop down list) Upload jpeg C. The programme checks the dimensions of the uploaded image against the type of banner selected. If false, display some error text If true, move on D. User is asked to select some promotional text from a drop down menu E. The programme finds the matching image (stored in a database?) and places it over the submitted image F. The result is displayed to the user. User approves by pressing a submit button G. The image is sent to a location that I can access There's lots of ways I want to expand this but, this would save me up to 3 weeks worth of work every month and give some time to do some thinking. I … -
Error Could not import 'django.views.defaults.server_error'
In the error logs for a Django site my error logs are filled with thousands of these errors: ViewDoesNotExist: Could not import 'django.views.defaults.server_error'. Parent module django.views.defaults does not exist. For all different views. Judging by the timestamps it looks like a bot hammers my site making multiple requests every millisecond, thousands in total and these errors get produced. Is there a way of finding out what the actual exception is and any solutions? -
How do I reference a matplotlib plot returned from a view in an html template in Django?
I am trying to interactively display plots from matplotlib in django. From this answer, I see that I can send the plot from a view with this code: response = HttpResponse(mimetype="image/png") # create your image as usual, e.g. pylab.plot(...) pylab.savefig(response, format="png") return response So the view sends the plot as an Httpresponse, but how do I reference that in the html code of the template? I'm guessing it will be something like this but am having a tough time finding examples of html code: <img src={ some reference to the plot here }> Again, I think I can generate the plot in with a view but am not sure how to reference that output in the html template. -
Django request.get_full_path is not working on mobile
Does anyone know why {% if request.get_full_path %} is not working on mobile browser? It just works as expected on desktop. -
Difference between save() and pre-save and post-save
**I'm a newbie in Django and I have the following questions, and I need your advice.the Django documentation is not enough for me as it is missing the examples ** **here we put .save() function: and don't know should i use pre/post ** def update_total(self): self.total=self.cart.total+self.shipping_total self.save() in the postsave function we didtn't put save() def postsave_order_total(sender,instance,created,*args,**kwargs): if created: print("just order created ") instance.update_total() post_save.connect(postsave_order_total,sender=orders) and with m2m signal we put .save function , is it true and if it is why we didn't put .save() in pre_save or post_save() def cal_total(sender,instance,action,*args,**kwargs): # print(action) if action=="post_add" or action=="post_remove" or action=="post_clear": prod_objs=instance.products.all() subtotal=0 for prod in prod_objs: subtotal+=prod.price print(subtotal) total=subtotal+10 instance.total=total instance.subtotal=subtotal instance.save() m2m_changed.connect(cal_total, sender=cart.products.through) in the m2m signal why I specified the action: if action=="post_add" or action=="post_remove" or action=="post_clear" Also in the the update , i didn't use save() with it qs = orders.objects.filter(cart=instance.cart,active=instance.active).exclude(billing_profile=instance.billing_profile) if qs.exists(): qs.update(active=False) -
django model.save() alternative without changing id
I noted that invoking 'save()' on an existing django object , the original id of the object will be changed when I just want to update some value of its attribute. So is there any method, e.g. update(?), on the object that allows me to do that, i.e. changing attribute values while remaining the same id? -
How do I make an IntegerField get autoincrement and not editable?
I have a field called "number", and would like it to be autoincrement and not editable. I have a system that has multiple users. Each user can register a document that follows an ordinal sequence. Each user can only create as many documents as he wants, but each document has its number generated in order, and should never be repeated. I tried using: number = models.IntegerField (unique = True) However, it occurs that if another user has already created a document with that number, another user can not create it. class Document(models.Model): date = models.DateTimeField(default=timezone.now) responsible = models.ForeignKey(Responsible, on_delete=models.PROTECT) from = models.CharField(max_length=80) work_from = models.CharField(max_length=80) subject = models.CharField(max_length=80) text = models.TextField() number = models.IntegerField() -
Who get correct value for join ManyToMany in Django?
I try to have the same result that this SQL query... SELECT * FROM my_BDD.Fernand, my_BDD.Fernand_has_Clothaire, my_BDD.Clothaire where Fernand.idFernand=Fernand_has_Clothaire.Fernand_idFernand AND Fernand_has_Clothaire.Clothaire_idClothaire=Clothaire.idClothaire; ...but with django. But, in django, it is a bit more complex to me to have the same result. After an inspectdb i have theses model from my_BDD models.py class Clothaire(models.Model): idclothaire = models.AutoField(db_column='idClothaire', primary_key=True) #otherfieds....... class Meta: managed = False db_table = 'Clothaire' class Fernand(models.Model): idfernand = models.AutoField(db_column='idFernand', primary_key=True) #others fields has_Clothaire = models.ManyToManyField(Clothaire, related_name='clothaires', through="FernandHasClothaire", through_fields=('fernand_idfernand', 'clothaire_idclothaire')) class Meta: managed = False db_table = 'Fernand' unique_together = (('idfernand'),) class FernandHasSt(models.Model): fernand_idfernand = models.ForeignKey(Fernand, models.DO_NOTHING, db_column='Fernand_idFernand') clothaire_idclothaire = models.ForeignKey('Clothaire', models.DO_NOTHING, db_column='Clothaire_idClothaire') #otherfields class Meta: managed = False db_table = 'Fernand_has_Clothaire' unique_together = (('fernand_idfernand', 'clothaire_idclothaire'),) So, i try this... view.py #just for the example def main(): clothaires = Clothaire.objects.all() fernands = Fernand.objects.all() createDataTableGeneral(clothaires,fernands) def createDataTableGeneral(clothaires,fernands): for f in fernands: for c in clothaires.filter(idclothaire__in=fernands.values('has_Clothaire')): print(c.anotherfield) And here, i have all the n-n combination... Thanks in advance for your answer. -
Django DRF ModelSerializer isvalid() always false when deserialize JSON
I'm apologize in advance for my poor english. Despite of all I found here , I don't find any solutions to my problem. I'm using django rest framework to work on REST API in Pycharm on Python 3.x http://www.django-rest-framework.org/api-guide/serializers/ When I use the ModelSerializer on my code, i can create a json from my model self.woodrow_attributes = {'name': 'RankA', 'gps_position_x': Decimal('40.15'), 'gps_position_y': Decimal('45.50'), 'gps_position_z': Decimal('30.50')} self.woodrow = WoodRow.objects.create(**self.woodrow_attributes) self.woodrow_serializer = WoodRowSerializer(instance=self.woodrow) data_json = JSONRenderer().render(self.woodrow_serializer.data,) my json is good and contains all information in bytes type : b'{"row_id":1,"name":"RankA","gps_position_x":"40.1500000","gps_position_y":"45.5000000","gps_position_z":"30.5000000"}' And when I want to deserialize it and test if the contents is valid, the answer is always false. I use ModelSerializer and when I run this code : deserialize_data = BytesIO(data_json) deserialize_data = JSONParser().parse(deserialize_data) print(deserialize_data) print(type(deserialize_data)) serializer = WoodRowSerializer(data=deserialize_data) print(serializer.is_valid()) print(serializer.error_messages) I got this : {'row_id': 1, 'name': 'RankA', 'gps_position_x': '40.1500000', 'gps_position_y': '45.5000000', 'gps_position_z': '30.5000000'} <class 'dict'> False {'required': 'This field is required.', 'null': 'This field may not be null.', 'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'} The error said that my data is invalid and datatype but I just print before that it is a dict. When I try my code in python console, it works and the serializer … -
Unable to implement jspdf using javascript?
I am trying to use jspdf to download a pdf and save it using javascript. Now, the problem is that when I try to execute jspdf function, I get this annoying error. I am using django with python. My goal is to be able to download the page using jspdf and then automatically trigger the print preview event for the user. What could I be doing wrong ?? jspdf.min.js:70 Uncaught TypeError: Cannot read property 'name' of undefined at k (jspdf.min.js:70) at r (jspdf.min.js:70) at r (jspdf.min.js:70) at r (jspdf.min.js:70) at r (jspdf.min.js:70) at jspdf.min.js:70 at i (jspdf.min.js:70) at v (jspdf.min.js:70) at x (jspdf.min.js:70) at Object.e.fromHTML (jspdf.min.js:70) This is what I tried so far. What could I be doing wrong? <div id="content"> <div class="mdl-grid"> <div> {% if messages %} <div > <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %} </div> </div> <div class="mdl-grid"> <!-- profile card --> <!-- Square card --> <style> .demo-card-square.mdl-card { {#width: 320px;#} min-height: 200px; max-height: 600px; } .demo-card-square > .mdl-card__title { color: #fff; min-height: 250px; max-height: 250px; background: url('/media/profile.png') bottom right 15% no-repeat #3C5D73; } {#.mdl-card__supporting-text {#} {# … -
HTML manifest caches the entire index page
I load all my files with ?v=x at the end but since I started using a manifest appcache for my website to load all the card images (about 80-90 images that need to be cached) I realized that when I make changes to the project, the browser does not update them at all. For example, you can see the version number in the page (http://royplus.herokuapp.com/) but when I deploy changes with a different version number, the browser doesn't render it at all, just cached index page. So how can I cache all my images and keep the index out of cache? -
How to display the value of the decorated @property on the html page?
I was asked to correct someone else's code. The man who wrote it, has long resigned. It seems to me that this should be done through the decorator @property. I'm trying to use the decorator @property in django version 1.10: Model: class TblReestr(models.Model): id = models.IntegerField(primary_key=True) # AutoField? ean13 = models.CharField(max_length=50, blank=True, null=True) reg_price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) trade_name = models.CharField(max_length=1000, blank=True, null=True) fabr_name = models.CharField(max_length=500, blank=True, null=True) reg_data = models.DateField(blank=True, null=True) mnn_name = models.CharField(max_length=250, blank=True, null=True) valuta_name = models.CharField(max_length=20, blank=True, null=True) num_prikaz = models.CharField(max_length=30, blank=True, null=True) @property def current_price(self): surcharge = 0 if (self.reg_price is None) or (self.reg_price == 0): return surcharge if self.reg_price < 50: surcharge = self.reg_price * 0.1173 + self.reg_price * 0.246 elif 50 <= self.reg_price <= 500: surcharge = self.reg_price * 0.12 + self.reg_price * 0.249 elif self.reg_price > 500: surcharge = self.reg_price * 0.1175 + self.reg_price * 0.243 return self.reg_price + surcharge class Meta: managed = False db_table = 'tbl_reestr' But the data is not output to the html page: {% elif target == 'reestr' %} <table class="table table-bordered table-condensed table" onselectstart="return false"> <thead> <tr class="info"> <th class="text-center">Наименование</th> <th class="text-center">Производитель</th> <th class="text-center">Цена</th> </tr> </thead> <tbody> {% for item in item_list %} <tr class="active"> … -
python Django command argument parsing returning an array
I have this simple Django command I'm writing as such: def add_arguments(self, parser): parser.add_argument('--type', nargs='+', type=str) parser.add_argument('--overwrite', nargs='?', type=bool, default=False) parser.add_argument('--unsubscribe', nargs='?', type=bool, default=False) def handle(self, *args, **options): print(options['type']) If I run myCommand --type=all I see my type printed as ['all']. Why is this coming back as an array? I just want the string value all. -
Why are session records not being saved in my Django app?
I have a Django (1.11.8) application running on a staging server on Heroku. I imported the database with existing records, users, etc and it all seems to be working fine. When I sign in, I am sometimes returned to the sign in page. Other times I am signed in and I'm redirected to the user profile page. However, if I do anything after that I end up getting signed out. I tried making sure the name of the cookies don't clash with the production application (which works fine). I also inspected Session records via the shell. When I manage to sign in, it doesn't look like it's creating any new session records. To be sure I cleared all the session records and no new ones get created when I sign in. The database connection seems fine, as I'm able to create a user record by signing up. I've also been able to manually create a session record via the shell. I just don't see any being created as a result of the sign in page. Any ideas appreciated? -
I need that my button close whenever i click javascript
I have a button for notification the problem is that it can be closed whenever I click... I need to press again on the button. I try to change the javascript like mouseout or something like this but nothing work. Django template : <div class="notification"> <span class="glyphicon glyphicon-bell"></span> {% if unread_notifications_count %} <div class="counter">{{unread_notifications_count}}</div> {% endif %} <ul class="notifications hidden"> {% for n in notifications %} <li class="{% if not n.read %} new {% endif %}"> <div class="icon"><img src="/static/img/icon-popup.svg"></div> <a href="{{n|notification_url}}"> {{n.text}} <div class="date" data-date="{{n.date.ctime}}">{{n.get_date}}</div> </a> <div class="clearfix"></div> </li> {% endfor %} <a href="{% url 'notification_list' %}"><div class="see-all">See all</div></a> </ul> </div> Javascript: initNotification(){ $('.notification').on('click', function(event){ $(this).find('.notifications').toggleClass('hidden'); }) CSS: .notification{ position: relative; float: left; // notification icon span.glyphicon{ font-size: 25px; padding-top: 6px; } .counter{ position: absolute; top: 0; z-index: 9999; right: -5px; color: red; border-radius: 50%; background: $red; color: $white; width: 17px; height: 17px; font-size: 12px; text-align: center; } &:hover{ cursor: pointer; } } -
Failed to process message due to a permanent exception with message Cannot submit message Django Outlook/hotmail
If someone had this issue, I will be sincerely thankful for your help. I'm having this error sending local email with hotmail: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/huey/consumer.py", line 169, in process_task task_value = self.huey.execute(task) File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 357, in execute result = task.execute() File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 842, in execute return func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/huey/contrib/djhuey/__init__.py", line 108, in inner return fn(*args, **kwargs) File "/code/app/tasks.py", line 89, in send_email email_message.send() File "/usr/local/lib/python3.6/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 127, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/local/lib/python3.6/smtplib.py", line 888, in sendmail raise SMTPDataError(code, resp) smtplib.SMTPDataError: (432, b'4.3.2 STOREDRV.ClientSubmit; sender thread limit exceeded [Hostname=DM5PR19MB1050.namprd19.prod.outlook.com]') ERROR process_task Unhandled exception in worker thread Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/huey/consumer.py", line 169, in process_task task_value = self.huey.execute(task) File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 357, in execute result = task.execute() File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 842, in execute return func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/huey/contrib/djhuey/__init__.py", line 108, in inner return fn(*args, **kwargs) File "/code/app/tasks.py", line 89, in send_email email_message.send() File "/usr/local/lib/python3.6/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 127, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/local/lib/python3.6/smtplib.py", line 888, in … -
AttributeError in Django 2 but not Django 1.11
The following code worked fine in Django 1.11, but in DJango 2 and up it fails: 'imageToLoad' : imageQ[0].imagePath The error is AttributeError: 'ImageFieldFile' object has no attribute 'replace' I was reading through the DJango 2 documentation but couldn't figure out what the issue is. Here is the entire code block: def getContextFromObject(request,imageQ): if (imageQ != None): imageJson = serializers.serialize("json", imageQ) print("image id is " + str(imageQ[0].id)) request.session['image_id'] = imageQ[0].id print("attempt to load: " + str(imageQ[0].imagePath)) # Below is the block that fails on DJango 2. Specifically, it is the first part, 'imageToLoad' : imageQ[0].imagePath context = {'imageToLoad' : imageQ[0].imagePath, 'imageWidthPixels': imageQ[0].widthPixels, 'imageHeightPixels': imageQ[0].heightPixels, 'imageMeasuredCenter': (imageQ[0].swMeasuredCenter).quantize(Decimal('.01'), rounding=ROUND_DOWN), 'micronsPerPixel': imageQ[0].micronsPerPixel, 'imageChannelSelect': imageQ[0].channelSelect, 'imageId' : str(imageQ[0].id), 'images' : imageJson } else: context = { } return context; -
Django Deploying 500 status when debug=False
I'm using django to build my own blog now and I think it's good.But now I've noticed a problem.When I change the debug var to False,System checks are OK but It'll return a 500 error status.When I change it to True,The bug won't happen again.So what's the problem?Can anybody help me? -
Django: How to pass a list of PKIDs to next view through AJAX, then redirect
Premise: The user is presented a table with a list of objects with checkboxes next to them. The user is able to check as many checkboxes as they want. The user then clicks a button that will redirect them to another page, that does stuff with only those objects that were selected. So I need to pass an array of object IDs I capture through jQuery to my next view (from here on GraphView) through a POST request embedded in a button, to show a list of only those objects on the next redirected page. How do I handle that in my URLs and in my view? My jQuery: // This is the event listener for the button click that would redirect you to the next page $("#graphRuns").click(function() { var array = []; // IDs come from checkboxes. You select which objects you want // in your next page, then click a button. Here I determine // which IDs to add to the array through a data-attribute // on my HTML object templates choiceContainer.find("input:checked").each(function() { var run_id = $(this).data("run_id"); array.push(run_id); }); // I checked and the list of IDs is correct. console.log(array) // So I do a post request to … -
"you don't have permission to edit anything" on custom AdminSite if user is not superuser
I wan't to have multiple AdminSite on my Django project and I don't want to give every user the superuser role just to see and edit the models of the application. Here is the layout of my project: > djangoApp > djangoApp - settings.py - etc... > AAA - admin.py - urls.py - etc.. > BBB - admin.py - urls.py - etc.. > CCC - admin.py - urls.py - etc.. > ressources - models.py - etc.. > core - admin.py - auth.py - models.py - views.py Here is the admin.py of BBB (I use a different database for each AdminSite): from django.contrib import admin from django.contrib.admin import AdminSite, site from core.admin import UserAuthenticationForm from ressources.models import Adresse class BBBAdminSite(AdminSite): site_header = 'BBB admin' login_form = UserAuthenticationForm login_template = "core/login.html" def has_permission(self,request): user = request.user return user.is_active and user.is_staff and (user.account_id == 100 or user.account_id == 0) class AdminModel(admin.ModelAdmin): using = 'DATABASE_NAME' def has_add_permission(self, request): user = request.user return user.is_active and user.is_staff and (user.account_id == 100 or user.account_id == 0) def has_change_permission(self, request, obj=None): user = request.user return user.is_active and user.is_staff and (user.account_id == 100 or user.account_id == 0) def has_delete_permission(self, request, obj=None): user = request.user return user.is_active and user.is_staff and …