Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to setup permissions to graphql relay queries in Django Graphql that uses JWT authentication
This is a recent problem I encountered in Django I setup a django backend server that serves a graphql api and I used Django Graphql JWT that offers auth functionnality the documentation is here the package offers decorators that can be setup with resolvers and it works perfectly with that, the issue occurs when I try to setup a relay query and would like to authorize that to logged users. Since the syntax to use relay in django excludes the use of a resolver method and therefore really don't know how to setup the authorization. Thanks in advance. -
Error messages when i want to pip install mysql-python and mysqlclient with MacOS
I'm currently working on a project using Django with python2.7 but each time I try pip install mysqsl I get this error messages "" ERROR: Command errored out with exit status 1: command: 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/setup.py'"'"'; __file__='"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/pip-egg-info cwd: /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/ Complete output (10 lines): sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 43, in get_config libs = mysql_config("libs_r") File "setup_posix.py", line 25, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output."" Any help please -
Intergrating Firebase with Django Rest Framework
So I have a Django back-end with a Firebase database and a React front-end. I want to POST data from the React to the Django which will Post to Firebase (I know i can do it all in JS to Firebase but i figure it might help more to have a python back-end for the future). I see tutorials using Django Rest Framework and I have been able to get that work but it uses SQLite3 and not Firebase. How can i implement Firebase into Django Rest Framework? -
An alternative to Chrome Dev Mobile Emulator?
I've known for a while now that the chrome mobile emulator can't get 100% accuracy, but it's driving me particularly nuts for a Django website I've been putting together. I know Safari has the option of using a Web Inspector on your phone by connecting to your laptop, but from what I've seen, that's only for Macs (unless I'm wrong, correct me if I am), and I do not have a Mac. Is there any alternative that allows me to get at least a closer percent of accuracy for mobile screens? Here are a few screenshots to show the problem. iPhone vs Chrome Dev Tools -
'url' tag for while using tornado (python), just like in Django Template Language
Like in Django, we can use DTL {% url 'url_name' %} instead of hard coding URL names. Is anything of that sort is available while using Tornado (python)? -
django- How do I get the drop down list of boards for the add task form to only show boards the user has created?
How do I get the drop down list of boards for the add task form to only show boards the user has created? The form shows all the boards that are in the database. How can i limit the dropdown list to just be the boards the user has created. models.py class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(unique=True) admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board") name = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) class Task(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) admin = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField(default=False) assigned_to = models.CharField(max_length=30) forms class CreateNewBoard(ModelForm): - some code- class CreateNewTask(ModelForm): text = forms.CharField(max_length=300, help_text="Please enter a task") assigned_to = forms.CharField(max_length=30, help_text="Assigned to") complete = forms.BooleanField(help_text="complete?") class Meta: model = Task fields = ('board', 'text', 'complete', 'assigned_to') views.py def create_task(request,username): form = CreateNewTask() if request.method == "POST": if username == request.user.get_username(): form = CreateNewTask(request.POST) if form.is_valid(): temp = form.save(commit=False) temp.admin = request.user temp.save() return redirect("/dashboard") return render(request, 'boards/task.html', {'form': form}) Task.html {% block title %}Task - {% site_name %}{% endblock %} {% block content %} <div class="mt-3"> <h1>Add a Task</h1> <form method="post" action="/{{ user.get_username }}/task/create/" id="create"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ … -
Threads can only be started once in Django channels
I created a simple Django Channels consumer that should connects to an external source, retrieve data and send it to the client. So, the user opens the page > the consumer connects to the external service and gets the data > the data is sent to the websocket. Here is my code: import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer, AsyncJsonWebsocketConsumer from binance.client import Client import json from binance.websockets import BinanceSocketManager import time import asyncio client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') bm = BinanceSocketManager(client) class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') bm.start_trade_socket('BNBBTC', self.process_message) bm.start() def process_message(self, message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] asyncio.create_task(self.send_json(Rate)) print(Rate) This code works when i open one page; if i try to open a new window with a new account, though, it will throw the following error: File "C:\Users\User\Desktop\Heroku\github\master\Binance\consumers.py", line 54, in connect bm.start() File "C:\Users\Davide\lib\threading.py", line 843, in start raise RuntimeError("threads can only be started once") threads can only be started once I'm new to Channels, so this is a noob question, but how can i fix this problem? What i wanted to do was: user opens the … -
How to add background image through css in django?
How to get the path to work so it shows the background image through css? If it could be done with a relative path then how? /*mobile view*/ .index-banner { background: url('static/mysite/images/home.svg') no-repeat; background-position: center; background-size: cover; width: 100%; height: 380px; } {% block content %} <section class="index-banner"> <h2>Test<br>Condiitons</h2> <h1>lorel ipsum</h1> <h1>sdfjls upueh ndsfoi bbownl</h1> <img src="{% static 'mysite/images/home.svg' %}" class="mysite-img" style="display: none;"> </section> {% endblock %} -
Django CMS Carousel
I am learning/developing my company website. and I really don't know how to add the correct plug-ins on this Carousel that I have and also integrate with all the translations. But static code bellow works fine, but I would like to convert that to the django-cms plugin format <header> <div class="container-fluid"> <div class="slider-container"> <div class="owl-slider owl-carousel"> <div class="item"> <div class="owl-slider-item"> <img src="{% static 'home/images/slide-1.png' %}" class="img-responsive" alt="portfolio"> <div class="intro-text"> <div class="intro-lead-in">Text1 Lead</div> <div class="intro-heading">Text1 Heading</div> </div> </div> </div> <div class="item"> <div class="owl-slider-item"> <img src="{% static 'home/images/slide-2.png' %}" class="img-responsive" alt="portfolio"> <div class="intro-text"> <div class="intro-lead-in">Text2 Lead</div> <div class="intro-heading">Text2 Heading</div> </div> </div> </div> <div class="item"> <div class="owl-slider-item"> <img src="{% static 'home/images/slide-3.png' %}" class="img-responsive" alt="portfolio"> <div class="intro-text"> <div class="intro-lead-in">Text3 Lead</div> <div class="intro-heading">Text3 Heading</div> </div> </div> </div> </div> </div> </div> </header> -
user=User.objects.get_or_create(first_name=fk_first_name,last_name=fk_last_name,email=fk_email)[0] why [0] is used
in this python code which is creating fake name with email : from faker import Faker from .models import User fk=Faker() def populate(N=5): for entry in range(N): fk_name=fk.name().split() fk_first_name=fk_name[0] fk_last_name=fk_last[1] fk_email=fk.email() user=User.objects.get_or_create(first_name=fk_first_name,last_name=fk_last_name,email=fk_email)[0] if __name__=='__main__': inp=int(input("please enter the integer value for population")) print('Populating ......................') populate(inp) print("population is done \n") in this user=User.objects.get_or_create(first_name=fk_first_name,last_name=fk_last_name,email=fk_email)[0] why [0] is used -
Pillow is not installing in Django when I creating a new Project
[ error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe' failed with exit status 2 ] When I created my first project Pip install pillow installed successfully but when I created a new project then pip install pillow was showing this error. I don't know what is happening with this. -
share dynamic object (not stored in DB) between views Django
my views.py from django.shortcuts import render from django.http import JsonResponse from home_page.models import UploadNet from home_page.forms import NetForm, ConfigForm from backend.NetListBuilder import NetListBuilder from backend.ConfigBuilder import ConfigBuilder def set_configuration(request, net_file=None): if "upload_net" in request.POST: net_path = os.path.join("media/net_files", net_file.name) netlist = NetListBuilder(net_path) config = ConfigBuilder(netlist) context = {'config': config,} return render(request,'configuration.html', context=context,) return render(request,'configuration.html', {'net_file': None},) def save_config(request): if request.is_ajax(): response_data = {} json_data = {} json_data = request.POST['json_data']: response_data["result"] = "save file" return JsonResponse(response_data) context = {'net_file': None} return render(request, 'rules_list.html', context=context) I want to share netlist and config objects (without saving them in DB) in rules_list view. how can i do that? should i pass them into configuration.html file? -
Mutiple bokeh Charts in django template
I don't understand how I can set up several Bokeh Chart in my django template. I have read this page https://docs.bokeh.org/en/latest/docs/user_guide/embed.html which supposed to explain this but it is not clear at all. Here is my view : def Bokehplot(request): source = ColumnDataSource(S.df) p = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc") p.line("date", "Te", source = source, line_width = 2,color = "green", alpha = 0.6) q = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc") q.line("date", "Tr", source = source, line_width = 2,color = "red", alpha = 0.6) plots = {'Red': p, 'Blue': q} script, div = components(plots) return render(request, 'batterie/results.html', locals()) {{div|safe}} gives the 2 divs on a row. I would like to access div1 (first graph) and div2 (second graph) in order to put them in 2 different bootstrap columns ? Any help is welcome. Thanks! -
Django queryset join tables
I am really stuck with merging two tables. I have tables Item and Transactions class Item(models.Model): category_choices = [] item_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=100, choices=category_choices) image = models.ImageField(upload_to='media') stock = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) date_added = models.DateTimeField(default=timezone.now()) class Transactions(models.Model): transaction_id = models.AutoField(primary_key=True) order_id = models.UUIDField() item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='transactions') quantity = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) address_str = models.CharField(max_length=100) address_plz = models.CharField(max_length=100) address_place = models.CharField(max_length=100) address_country = models.CharField(max_length=100, choices=[(name[1], name[1]) for name in countries]) Now I want to render template with transactions and images and items info from Item model. I am trying to use prefetch_related, howeve rit does not work and I do not understand how this should be solved. def order_history(request): if request.user.is_authenticated: transaction = Transactions.objects.order_by('-transaction_date').\ filter(username=request.user).prefetch_related('item') context = {'orders': transaction} template_name = 'retail/order_history.html' return render(request, template_name, context=context) else: raise Http404('You are not authorised') -
Completely stuck, Cannot resolve keyword 'user' into field Django
So, I'm completely stuck. I have been stuck on this for days now. I'm not sure exactly what's going on here, as I'm totally new to django. I've read over the docs, and I've looked up things on here, but there's not much. I'm basically trying to having profiles display on a page that I've already created. I'm using a custom user model. Would truly appreciate some help. And the thing is, I was suggested to simply take out 'user' in 'user=request.user, but problem is if I do that, than I get 'Profile' is not iterable. error at line 'description = Profile.objects.get(user=request.user).description' : FieldError at /mingle/ Cannot resolve keyword 'user' into field. Choices are: date_joined, description, email, given_vote, id, is_active, is_admin, is_staff, is_superuser, last_login, logentry, matches, password, photo, username, uservote Request Method: GET Request URL: http://localhost:8000/mingle/ Django Version: 2.2.3 Exception Type: FieldError Exception Value: Cannot resolve keyword 'user' into field. Choices are: date_joined, description, email, given_vote, id, is_active, is_admin, is_staff, is_superuser, last_login, logentry, matches, password, photo, username, uservote Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py in names_to_path, line 1420 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 Python Version: 3.7.3 Python Path: ['/Users/papichulo/Documents/DatingAppCustom', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/papichulo/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Server time: Sun, 5 Apr 2020 19:20:01 +0000 views.py def mingle(request): … -
AJAX and Django with Javascript
I trying to work on ajax and django. but its not working and i dont know where i went wrong function hr(){ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { hrr(this); } }; xhttp.open("GET","{% url 'sc' %}"); xhttp.send(); } function hrr(xml) { var i; var xmlDoc = xml.responseXML; var x = xmlDoc.getElementsByTagName("object"); var table=""; for (i = 0; i <x.length; i++) { table +=x[i].getElementsByName("search_name")[0].childNodes[0].nodeValue + "<br>" ; } document.getElementById("disp").innerHTML = table; } <button onclick="hr()"> hr</button> <div id="disp">h</div> url.py path("search-car", views.search_car, name='sc'), views.py def search_car(request): scn=Car.objects.filter(search_name__icontains='au') data = serializers.serialize("xml", scn) return HttpResponse(data,status_code=200) xml file This XML file does not appear to have any style information associated with it. The document tree is shown below. <django-objects version="1.0"> <object model="pages.car" pk="1"> <field name="name" type="CharField">Audi</field> <field name="name2" type="CharField">Q7</field> <field name="search_name" type="CharField">Audi Q7</field> </object> </django-objects> Please let me know where i went wrong -
Show Database Items related to user logged (Django)
In my website when a User log in he's redirected to his profile page. Now I'd like to see all the items he stored in the database. How could I do? Thanks Here's the views.py. This is the page the user is redirected to after the login class userView(TemplateView): template_name = 'search/user.html' Html file: <div class="add"> <div class="posted"> {% if objects_list %} {% for o in objects_list %} <div class="container_band"> <div class=album_band> <!-- insert an image --> <img src= "" width="100%"> </div> <div class="info_band"> <!-- insert table info --> <table> <tr><th><h2>{{o.band}}</h2></th></tr> <tr><td> Anno: </td><td> {{o.anno}} </td></tr> <tr><td> Disco: </td><td> {{o.disco}} </td></tr> <tr><td> Etichetta: </td><td> {{o.etichetta_d}} </td></tr> <tr><td> Matrice: </td><td> {{o.matrice}} </td></tr> </table> </div> </div> {% endfor %} {% endif %} </div> models.py class Info(models.Model): utente = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) band = models.CharField(max_length=200) disco = models.CharField(max_length=200) etichetta_p = models.CharField(max_length=200) etichetta_d = models.CharField(max_length=200) matrice = models.CharField(max_length=200) anno = models.PositiveIntegerField(default=0) cover = models.ImageField(upload_to='images/', blank=True) def __str__(self): return self.band class Meta: verbose_name_plural = "Info" ordering = ['anno'] -
'utf-8' codec can't decode byte - Python
My Django application is working with both .txt and .doc filetypes. And this application open file, compares it with other files in db and prints out some report. Now the problem is that, when file type is .txt, I get 'utf-8' codec can't decode byte error (here I'm using encoding='utf-8'. When I switch encoding='utf-8' to encoding='ISO-8859-1' error changes to 'latin-1' codec can't decode byte. I want to find such encoding format that work with every type of file. This is my a little part of my function: views.py: @login_required(login_url='sign_in') def result(request): last_uploaded = OriginalDocument.objects.latest('id') original = open(str(last_uploaded.document), 'r') original_words = original.read().lower().split() words_count = len(original_words) open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-5.txt", 'w') # Path to the documents with which original doc is comparing path = 'static/other_documents/doc*.txt' files = glob.glob(path) rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files) context = { ... } return render(request, 'result.html', context) -
No path found on Django Channels
I created a simple consumer on my Django channels application, but when i try to connect to the websocket from my frontend, i keep getting the following error: ws_protocol: ERROR - [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'messages/127.0.0.1:8000/messages/'. Here is my routing: myapp>routing.py from .consumers import EchoConsumer websocket_urlpatterns = [ path("messages/", EchoConsumer), ] mysite>routing.py # mysite/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import myapp.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( myapp.routing.websocket_urlpatterns ) ), }) And here is how i'm trying to connect to the websocket from my frontend: var wsStart = 'ws://' + window.location.host + window.location.pathname Can anyone help me find what i'm doing wrong, please? -
Passing parameters using action tag in HTML
I'm working with Tornado (python), and my handlers are in this format. class Application(tornado.web.Application): def __init__(self): handlers = [ url(r'/', MainHandler, name="main_handler"), url(r'/user', UserHandler, name="user_handler"), url(r'/users', UserListHandler, name="user_list_handler"), url(r'/profile/(?P<username>\w+)', UserProfileHandler, name="user_profile_handler"), ] settings = dict( template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__),"static"), debug = True) self.db = client['user_db'] super().__init__(handlers, **settings) My HTML code on the landing page is <h1>INFO DB</h1> <p>Search via username...</p> <form method="get" action="{% url 'user_profile_handler' find_username %}"> <p>Enter Username<br> <input rows=1 cols=20 name="find_username"></p> <input type="submit"> </form> <br> Now my aim is when I click on the submit button, I'm redirected to the page '/profile/{username} Eg: if the username in the search bar is 'abcd', I should be redirected to /profile/abcd on pressing submit. What to put in the action attribute of the form tag in HTML? -
Django Rest Framework is serializing an object two different ways using the same serializer
When using a DRF ViewSet and an APIView, I get two different results for serialization of a DurationField. At the first endpoint host/app/items, which corresponds to the viewset Items and lists all of the created items, I get this response: [ { "id": 2, "duration": "604800.0", ... } ... ] The response from host/app/user_data includes the items corresponding to the item instances which have a relation to the profile: { ... "items": [ { "item": { "id": 2, "duration": "P7DT00H00M00S", ... } ... } ] } But the duration is in the ISO 8601 duration format. This was very perplexing, because the endpoints use the same serializer. I confirmed this by forcing the serializing with duration = serializers.DurationField() in ItemSerializer. I want the same format, in seconds. What can I do? These are issues I found while researching this issue: https://github.com/encode/django-rest-framework/issues/4430 https://github.com/encode/django-rest-framework/issues/4665 Urls: router = routers.DefaultRouter() router.register(r'items', views.Items) urlpatterns = [ path('', include(router.urls)), path('user_data', views.UserData.as_view(), name='user_data'), ... ] Views: class Items(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer def get_permissions(self): if self.action in ('list', 'retrieve'): permission_classes = [AllowAny] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] class UserData(APIView): """Get authenticated user's information: data related to models User and Profile""" … -
View Flow and Django Guardian
I am relatively new to django-guardian and django-viewflow , am still trying to wrap my head around things. Recently i have been attempting to implement a workflow system to get approvals on certain documents. As such i have chosen view flow workflow engine. The workflow that i have been tasked on developing is actually pretty simple and linear. However , at every check point , there must be a different person with a specialized role to verify the documents. There is 4 roles, 1 the preparer , 2 the verifier , 3 the treasury and 4 the Director. As i can't have someone verifying for the Director himself , there is a need for a role based user control. As such , i have adopted django guardian to do this job. Here is some of my code to demonstrate how i did it : Flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess lock_impl = lock.select_for_update_lock #process starts here start = flow.Start( CreateProcessView, fields=["paymentVoucher"], task_title="Processing New Voucher" ).Permission("can_start_voucher", auto_create=True ).Next(this.documents) #preparer will upload supporting documents documents = flow.View( UploadView, task_title="Receiving Supporting Documents" ).Permission("preparer", auto_create=True ).Next(this.preparer) #i wont go in detail as it isn't relevant Models.py this is where i defined my permissions , … -
How to deal with large amounts of data from django based IOT projects
I'm working on a django IOT related dashboard style project. I have a question related to the scale of the project. Let's say that there are 30 or more raspberry pi's or ardunios and you want to get the location and some other data off of them and store it in a database. How would one go about designing a database for a system at such a large scale. -
Compare two tables in Django
I am displaying data from Table1 in my template as seen below, I recently created another model called Table2 which contains data which I would like to display in my table as well. I need to check if the code in Table1 exists in Table2, and if so, grab the var1 and var2 from Table2 and display it in my template. Does anyone know how to do this the best way? Pseudocode If `code` In Table1 Exists In Table2 Get var1, var2 From Table2 My template {% for data in info %} <tr> <td>{{ data.created }}</td> <td>{{ data.publisher }}</td> <td>{{ data.person }}</td> <td>{{ data.code }}</td> </tr> {% endfor %} My view def home(request): info = Table1.objects.all()[:20] return render(request, 'app/home.html', {'info':info}) My models.py class Table1(models.Model): created = models.DateTimeField(default=None) publisher = models.CharField(max_length=50, default=None) person = models.CharField(max_length=50, default=None) code = models.CharField(max_length=25, default=None) class Meta: db_table = 'Table1' unique_together = (("publisher", "person", "code"),) def __str__(self): return self.created class Table2(models.Model): code = models.CharField(max_length=30, default=None, null=True) url = models.CharField(max_length=100, default=None, null=True) var1 = models.CharField(max_length=50, default=None, null=True) var2 = models.CharField(max_length=50, default=None, null=True) def __str__(self): return self.code -
Cannot register more than two classes in the Django admin
I am trying to register three classes to the admin. If I pass two classes it works perfectly but when I add the third I get the following error. I tried to pass three of then separately and that didn't work too. This is the my Django admin.py file: from django.contrib import admin from .models import Sensor from leaflet.admin import LeafletGeoAdmin from import_export.admin import ImportExportModelAdmin class Sensor_admin(LeafletGeoAdmin): list_display = ('subsystem', 'datasheet') class Sensor_io_Admin(ImportExportModelAdmin): pass admin.site.register(Sensor, Sensor_io_Admin, Sensor_admin) This is the error I got: TypeError: register() takes from 2 to 3 positional arguments but 4 were given What can be the way around it? I am using Django 2.1 version.