Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Messaging App With Django
I'm trying to build a messaging app, here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") ... created_at = models.DateTimeField(auto_now_add=True) I wants to order the Users based upon who sent a message to request.user & to whom request.user sent a message most recently! As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message (It re-orders their name & place it to the top). But, It's not changing the order of users in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. Also, I have to use {{ users.sender }} OR {{ users.receiver }} in order to print the users name which is a problem itself in case of ordering & distinct users. Please help me, how can I do that? -
How to pass JavaScript variables to React component
I'm somewhat new to React and I'm having some trouble passing some variables from my Django server to my React components. Here's what I have: The server is Django, and I have a url mydomain.com/testview/ that gets mapped to a views.py function testview: def testview(request): now = datetime.datetime.now() return render(request, 'testview.html', { 'foo': '%s' % str(now), 'myVar': 'someString' }) In other words, running testview will render the template file testview.html and will use the variables foo and myVar. The file testview.html inherits from base.html which looks like this: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> </head> <body> {% block main %}{% endblock %} </body> </html> The file test.html basically inserts the needed code into block main: testview.html: {% extends "base.html" %} {% load render_bundle from webpack_loader %} {% block main %} <script type="text/javascript"> var foo = {{ foo }}; var myVar = {{ myVar }}; </script> <div id="App"></div> {% render_bundle 'vendors' %} {% render_bundle 'App' %} {% endblock %} Note that just before the div id="App", I created a couple of javascript variables foo and myVar and set them to the values from Django. Now to REACT: my file App.jsx looks like this: import React from … -
Django: Can you format DateTimeField in annotate?
I have Customer and Order models and I would like to get the last order date of each customer and format it. I have the following code in views: customers = ( User.objects .prefetch_related('orders', 'addresses') .select_related('default_billing_address', 'default_shipping_address') .annotate( num_orders=Count('orders', distinct=True), last_order=Max('orders', distinct=True), last_order_date=Max('orders__created', distinct=True), gross_sales=Sum('orders__total_net'))) last_order_date is returning date in this format: Nov. 1, 2017, 11:39 p.m. I would like to update it so it returns 11/01/2017 only. How can I achieve this? I tried this: last_order_date=Max(('orders__created').strftime("%d/%m/%Y"), distinct=True), but it turns out ('orders__created') is already returning an str, I got this error: 'str' object has no attribute 'strftime' I also tried creating a method in orders that will return a formatted created field: def get_day_created(self): self.created.strftime("%d/%m/%Y") but i'm not sure if I can call it in annotate and how to properly do it. 'orders__get_day_created()' is giving me the error: Cannot resolve keyword 'get_day_created()' into field. Please advise :) Thank you -
Need to get data from News APIs into a django application, run it through an algorithm and store the same in a database
I am trying to make a news summarizing application. Although my algorithm seems to be working, I am having trouble making the web application. -
django how to authenticate user until verify email
How to authenticate user until he verify the email? In my sign up process, I create the User, which means he can login even without verify email. Is there a build-in method to set a un-verified status on a User? -
Django - Cannot assign "'Biography test'": "User.biography" must be a "Biography" instance
I have extended the user model with an extra field - biography. It appears in the admin panel as a new section. Here's a picture: Here's the new model: class Biography(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) biography = models.TextField(max_length=500, blank=True) Here's the profile view: def profile(request, username): user = get_object_or_404(User, username=username) products = Product.objects.filter(user=user) if not request.user == user: return render(request, 'no.html') else: return render(request, 'profile.html', {'user':user,'products': products}) I'm using a form to edit the profile - here's the view: def edit_profile(request): user = request.user products = Product.objects.filter(user=user) form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'biography':user.biography}) if request.method == 'POST': if form.is_valid(): user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.biography = request.POST['biography'] user.save() return render(request, 'profile.html', {'user':user, 'products':products}) context = {"form": form} return render(request, "edit_profile.html", context) ...and here's the form: class EditProfileForm(forms.Form): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') biography = forms.CharField(label='Biography', widget=Textarea(attrs={'rows': 5})) Here's a screenshot of the error message: I'm mixing something up but I can't figure out what. Doesn't help that I'm new to this ...still trying! -
Using React with Django, do I need react-router
Suppose I have an existing Django webapp with a bunch of urls in urls.py. Now suppose I want to add a number of webpages to this Django app, where the new webpages are built using React. From what I understand, React has its own routing capability (in react-router) so that if I go to mydomain.com/page1/ it will serve one thing and if O go to mydomain.com/page2/ it will serve something else. But what if I don't want to use react-router? In other words, if I have say 10 new pages to add and each page will have its own URL, then why can't I just set this up in Django's urls.py file? Currently in urls.py I have a url defined like this: url(r'^testview/', views.testview), In views.py I define testview like this: def testview(request): return render(request, 'testview.html', {}) My Django templates are stored in a folder BASE_DIR/myproject/templates/ and I set the TEMPLATES variable inside BASE_DIR/myproject/settings.py so Django knows where to find the templates. So in my view method above, "testview.html" refers to BASE_DIR/myproject/templates/testview.html. The contents of that file are: {% extends "base.html" %} {% load render_bundle from webpack_loader %} {% block main %} <div id="App1"></div> {% render_bundle 'vendors' %} {% render_bundle … -
What is the best way to increment an integer at a certain rate over time using a Django powered site and SQLite?
I am trying to display a number that will increment over time that is called from a very, very simple Django database. It will be called using jinja2 templating and the number is a simple IntegerField(). However, I would like for that number to autoincrement, live without refreshing the page, multiple times throughout the day. Also, I would like for every time that the number is refreshed, for the new value to be added to the same database recording the time and date. What is the best combo or group of languages/frameworks to achieve this? I'm starting to think that Django and Jinja2 alone are not enough to achieve this effect. -
i want to use manage.py in c9
i want to use django at c9.io but i try python manage.py migrate (or makemigrations) :~/workspace (master) $ python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 398, in execute self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/ubuntu/workspace/gettingstarted/urls.py", line 18, in url(r'^', include('hello.urls')), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/init.py", line 52, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/ubuntu/workspace/hello/urls.py", line 2, in from . import views File "/home/ubuntu/workspace/hello/views.py", line 9, in from . import connect_apiai,papago File "/home/ubuntu/workspace/hello/connect_apiai.py", line 8, in import urllib.request ImportError: No module named request -
django annotate weird behavavior (group by model.id)
In my DRF API, I have a view like this class ActivityAPI(viewsets.ModelViewSet): authentication_classes = (SessionAuthentication, TokenAuthentication) serializer_class = ActivitySerializer queryset = Activity.objects.order_by('-id').all() filter_backends = (DjangoFilterBackend,) filter_class = ActivityFilter filter_fields = ('name', 'ack', 'developer', 'ack_date', 'ack_by', 'verb') def get_count(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if CASE_1: queryset = queryset.values('verb').annotate(count=Count('verb')) if CASE_2: queryset = Activity.objects.values('verb').annotate(count=Count('verb')) return Response(data=queryset) In CASE_2, I got what i expected which is equivalent to SQL query SELECTactivity_activity.verb, COUNT(activity_activity.verb) AScountFROMactivity_activityGROUP BYactivity_activity.verbORDER BY NULL But when it's comes to CASE_1, the annotate feature groups the queryset by activity.id , that is SELECTactivity_activity.verb, COUNT(activity_activity.verb) AScountFROMactivity_activityGROUP BYactivity_activity.idORDER BYactivity_activity.idDESCNOTE I need url based filtered data for both API and Aggregation -
Django conflict with Conda
This the error that am getting when am running my server begin snippet: js hide: false console: true babel: false BASH language: lang-python --> Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x102994bf8> Traceback (most recent call last): File "/Users/sriharikapu/anaconda/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/sriharikapu/anaconda/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/sriharikapu/anaconda/lib/python3.6/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/Users/sriharikapu/anaconda/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/sriharikapu/anaconda/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/sriharikapu/anaconda/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/sriharikapu/anaconda/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/sriharikapu/anaconda/lib/python3.6/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/Users/sriharikapu/anaconda/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked end snippet -
Context processors - behind the scenes
I can't believe there is no other thread on that subject. Even the documentation seems really unclear to me. So here it is: What is the mechanics behind context processors in Django? I have used them before, but if someone asks me to teach them what context processors are about, I probably could not answer. This is from Django documentation: context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context. Can someone elaborate on this. How does that works behind the scene ? -
Django Rest Framework ModelSerializer create if not exists
I'm using Django Rest Framework 3.6.3. I'm trying to write nested create serializers for one optional argument and one required argument inside a child. I know that I need to override create in the base serializer to tell DRF how to create the nested children - http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers. However, I can't figure out how to get it to parse the object information without telling it what the nested child serializer is defined as. Doing that then causes DRF to use it to parse the children objects, which then returns a validation error that I have no control over because the child serializer doesn't call its create method. Base Specification(many=True) OptionalField RequiredField The information I pass in is a JSON object: { base_id: 1, base_info: 'blah' specifications: [ { specification_id: 1, optional_info: { optional_id: 1, optional_stuff: 'blah' }, required_info: { required_id: 1, required_stuff: 'required', } } ] } The BaseCreationSerializer calls it's create method. I know that I need to pull out the rest of the information and create it manually. However, I can't figure out how to get the BaseCreationSerializer to parse the data into validated_data without defining specification = SpecificationCreationSerializer(), which then tries to parse that and throws an error. … -
Django Models: The default value for booleanfield did not get set in MariaDB
Django: 11.1 MariaDB: 10.2.6 In models.py, I set a boolean field as follows: class myClassName(models.Model): class Meta: db_table = 'mytablename' verbose_name = 'name' verbose_name_plural = 'names' ordering = ['myid'] (several fields defined here...) myField = models.BooleanField(verbose_name='name', default=True, help_text='some help here') def __str__(self): return str(self.myid) Then, do 'makemigrations' and 'migrate' Afterwards, I can see the table well defined in MariaDB, however default values are not set for the BooleanFields. The fields are defined as tinyint(1), Default=NULL. Do I need to set some other value in the field definition, in order to properly configure the default value in the database? -
Django, ajax upload file with extra data
I have a little question, I want to upload a file with some extra data. So what I'm doing now is: JS file: $(document).on('submit', '.upload-file', function(e){ e.preventDefault(); var form_data = new FormData($(this)); //I dont know why, but it used to return None //so I append file and some extra data form_data.append( 'file', ($(this).find('[type=file]')[0].files[0]) ); form_data.append( 'expire', ($(this).find('.document-id').val()) ); form_data.append( 'document', ($(this).find('[type=datetime-local]').val()) ); $.ajax({ type : 'POST', url : 'some_url', data : form_data, cache: false, processData: false, contentType: false, }).done(function(data) { console.log(data); }); }); Views.py def upload_file(request): if request.method =='POST': data = request.POST.get('data') file = request.FILES print('File ->', file) #this one prints File print('Data ->', data) #this one prints None return HttpResponse() Printed data: File -> <MultiValueDict: {'file': [<InMemoryUploadedFile: MyFile.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)>]}> Data -> None So, I need to send file to external Server, which requeres some extra information, but I have no idea how to combine this data... Thnx everyone! -
Cannot connect Nginx with uwsgi +Django
What I've tried: 1. Nginx is fine, can access 80 port and see the default page 2. uwsgi + django is fine, I can use uwsgi to start my django app and access it ,with command: uwsgi --http :8000 --module webapps.wsgi the problem come out when I connect uwsgi to nginx 2017/11/07 01:36:47 [error] 27958#27958: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 71.61.176.181, server: 104.196.31.159, request: "GET / HTTP/1.1", upstream: "uwsgi://127.0.0.1:8001", host: "104.196.31.159:8000" here is the mysite.conf for nginx # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { #server unix:///home/liuziqicmu/ziqil1/homework/6/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name xx.xx.xx.xx(my ip); # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/liuziqicmu/ziqil1/homework6/grumblr/upload; # your Django project's media files - amend as required } location /static { alias /home/liuziqicmu/ziqil1/homework6/static; # your Django project's static files - amend as required … -
max_digits for IntegerField Django
I am looking for a way to specify an IntegerField so that it has a certain maximum of digits. What I'm looking for is similar to max_length of a CharField. I have searched the internet and even in this forum, but they are all answers related to adding minimum and maximum values such as min_length and max_length or adding validators. So that they do not get confused, what interests me is to establish an IntegerField with a maximum of digits and not a maximum value. Is there a function that can provide me so that in the model a parameter can be added to this IntegerField? E.g.: code = models.IntegerField('Code', primary_key=True, max_digits=8) -
How can i restrict date field in Django
im trying to make a Schedulle System using django. I wanna restrict the Date Field(in models.py) for only monday to friday. In sum, i want to restrict saturday and sunday from date field. How can i do that ? -
How can I do datatable filter request in a table using data that comes from another table in Django?
I testing a application that has 2 datatables. I am using django_tables2 and django_filter The first has one button per row, each when it is clicked it should extract a content from the second column of its row and applies this data to request and display the second table bellow considering the filter request. I am quite lost.. How could I do that??? Please any help?? Table.py class MyColumn(tables.Column): empty_values = list() def render(self, value, record): return mark_safe('<button id="%s" class="btn btn-info">Submit</button>' % escape(record.id)) class AdTable(tables.Table): submit = MyColumn() class Meta: model = Ad attrs = {'class': 'table table-striped table-bordered table- hover','id':'id_ad'} class PtTable(tables.Table): class Meta: model = Pt attrs = {'class': 'table table-striped table-bordered table- hover','id':'id_pt'} HTML <body> <div> <h1> "This is the Table" </h1> </div> <div> <table> {% render_table ad_table %} </table> </div> <div> {% block content %} <div> <form method="get"> {{ form.as_p }} <button type="submit">Search</button> </form> </div> {% endblock %} </div> <div> <table> {% render_table pt_table %} </table> </div> <script> $(document).ready(function(){ $('#id_ad').DataTable(); $('#id_ad').on('click','.btn',function(){ var currow = $(this).closest('tr'); var result = currow.find('td:eq(1)').text(); document.getElementById('total').innerHTML = result; }) }); </script> </body> Filter.py class PtFilter(django_filters.FilterSet): class Meta: model = Pt fields = ['var1', 'var2', 'var3', ] Views.py def index(request): ad_table = AdTable(Ad.objects.all()) … -
invalid literal for int() with base 10: '...aa53' - Django
I have a django project and I am trying to save something into my database from a json response. The field in the table is a charfield. the returning response is a string. I want to simply save the response in the database by create a new database object. I am getting the following error an I am not sure why this is happening. invalid literal for int() with base 10: '5..6003463aa53' Here is the code that I have: for node in nodes: node_json = node.json node_id = node_json['_id'] print(node_id) node_name = node_json['info']['nickname'] print(node_name) node_class = node_json['info']['class'] print(node_class) node_bank_name = node_json['info']['bank_name'] final_bank_name = str(node_bank_name) print(node_bank_name) new_account = SynapseAccounts.objects.create( user = currentUser, name = node_name, account_id = node_id, account_class = node_class, bank_name = final_bank_name, ) print(new_account) I even forced the string. Here is the model that I have for the table: class SynapseAccounts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, default='Bank Account') account_id = models.IntegerField(default=0) account_class = models.CharField(max_length=50, default='Checking') bank_name = models.CharField(max_length=150, default='DefaultBank') create = models.DateTimeField(auto_now_add=True) Here is the full stack trace Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response … -
request.user.attribute returning unwanted value
Why does the following print(owner) return a different value that what's in my model? Is it possible to get the formattedusername defined below? I've simplified my def profile(request) and took out my other arguments till I can figure out the solution to getting formattedusername. def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) args = {'user':request.user.formattedusername} print (owner) return render(request, 'accounts/profile.html', args) Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. @HFA9592 [06/Nov/2017 16:18:11] "GET /account/profile/ HTTP/1.1" 200 1416 formattedusername in my model is stored in the database as HCA\HFA9592, it's also defined by the following: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) facility = models.CharField(max_length=140) jobdescription = models.CharField(max_length=140) positiondescription = models.CharField(max_length=140) coid = models.CharField(max_length=5) streetaddress = models.CharField(max_length=140) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); -
Django order_by many to many relation
How would one go about ordering a queryset by whether or not a many to many relationship condition is true? i.e. class Publication(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book) class Book(models.Model): name = models.CharField(max_length=100) author = models.CharField(max_length=100) I would like to make a queryset along the lines of Publication.objects.all().order_by('books__name'='Awesome Book') So that the first items would be the Publication which contains a Book with the title "Awesome Book" and then in the end you have all the Publication's which do not have the book. -
Django/Jinaja2: How to store a dictionary object to a session from a template using a button?
I got a table that acted like a gridview which display fruit and price and also a button that allow the user to store the selected row data (fruit and price) upon clicked on it. For example, if the user clicked on the button of row which contain fruit = apple and price = 1, fruit = apple and price = 1 will be stored in a dictionary variable x and y in fruit_price = {'fruit': x, 'price': y} and finally stored it to a session. Is it possible to do so? result.html <table> <tr> <th>Fruit</th> <th>Price</th> <th>Store to Session</th> </tr> {% for fruit, price in fusion %} <tr> <td>{{ fruit }}</td> <td>{{ price }}</td> <td><button type="button" value="">Store It!</button></td> </tr> {% endfor %} </table> view.py def result(request): ss = request.session.get('store', ?) request.session['store'] = ss data = { 'fruit' : ['apple', 'orange', 'banana'] 'price' : ['1', '2', '3'] } fruit = data['fruit'] price = data['price'] fusion = zip(fruit, price) return render(request, 'result.html', {'fusion' : fusion}) -
Django menu & childmenu from models
I'm trying to a menu system for my sport site project where the sports are grouped together. For example the main category would be "ballsports" and under that (the child menu) people would select football, baseball or whatever else. I've got that all setup and functioning but I can't workout how to call the child menus into the templates. Models: class Sport(models.Model): name = models.CharField(max_length=100, db_index=True) sport_slug = models.SlugField(max_length=100, db_index=True) category = models.ForeignKey('Sport_Category', on_delete=models.CASCADE,) class Sport_Category(models.Model): name = models.CharField(max_length=100, db_index=True) category_slug = models.SlugField(max_length=100, db_index=True) Views: class IndexView(generic.ListView): template_name="sports/index.html" context_object_name='all_sport_category' def get_queryset(self): return Sport_Category.objects.all() def list_of_sports_in_category(self): sport_cat = self.category.name return sport_cat class SportListView(generic.ListView): template_name="sports/sport-home.html" context_object_name='sport_list' def get_queryset(self): return Sport.objects.all() Template: {% for sport_category in all_sport_category %} <li>{{ sport_category.name }} </li> *(Working)* {% for sports in list_of_sports_in_category %} hi {% endfor %} {% endfor %} -
How to make Django-CMS and Open Edx use same authentication for users?
We are looking to develop a Django project in which we need to integrate three different Django packages namely a CMS (Django-CMS or Wagtail), a LMS (Open edX) and a support/ticketing system. Since Django-CMS, Open Edx have their own user authentication, but we want them to share a common authentication (username, password, user profiles), so that a user logged into one section of website is able to move to other sections smoothly. How to make these different packages share same authentication? Is there any guidelines or procedure to integrate these different Django Packages? (Google search about such integration of packages doesnot have any clear documentation, so I decided to ask this on stackoverflow)