Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DoesNotExist --Matching Query Error
I'm trying to list a group of deals by category I have a Deal model and a Category Model, where the Category is a Foreign Key of a Deal like so: class Deal(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=140, unique=True) description = models.TextField(default='') category = models.ForeignKey(Category) The urlpattern for a category page looks like this: url(r'^category/(?P<category>\w+)/$', deals_by_category, name='category') The view for this urlpattern is this: def deals_by_category(request,category): category_deals = Deal.objects.filter(category__name=category, ) return render(request, 'deals/category.html', {'category_deals': category_deals}) and then my category.html template is looping through these returned deals like this: {% for deal in category_deals %} <h5 class="card-retailer">{{ deal.retailer}}</h5> <p class="card-title">{{ deal.title }}</p> Now the issue arises if i click on predetermined category link like this: http://localhost:8000/deals/category/Apparel/ but the error is pointing NOT to my 'deals_by_category' view, but to the individual view for each deal---the stack trace is pointing to that second line below. I think this must be an easy fix, but have been staring at this for the past few hours and can't determine what the issue is. def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) -
Django sort and regroup multiple fields
I am trying to regroup a field and sort on another in Django. My use case is different, but let's use the Django regroup template as an example. Using this dataset. cities = [ {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'}, {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'}, {'name': 'New York', 'population': '20,000,000', 'country': 'USA'}, {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'}, {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'}, ] Using the regroup tag, this is the output: India Mumbai: 19,000,000 Calcutta: 15,000,000 USA New York: 20,000,000 Chicago: 7,000,000 Japan Tokyo: 33,000,000 How can I sort this information by population and yet still keep the grouping? This is the expected output that I would like to see: Japan Tokyo: 33,000,000 USA New York: 20,000,000 Chicago: 7,000,000 India Mumbai: 19,000,000 Calcutta: 15,000,000 How would one query the database to keep the groupings that are needed for reorder in the Django template to work properly and yet still maintain the sort order of population? How would this work on a date object instead of an int? -
DJango TypeError - JSFiles object is not reversible
I am trying to include this datepicket widget in my DJango version 2.0.2, but it raises error TypeError at /xuser/1/edit 'JSFiles' object is not reversible I have already looked around for similar errors in following threads What does it mean by object not reversible Django TypeError at /admin/ 'set' object is not reversible But these are just typo errors about urlpatterns and does not even disclose what reversible actually mean in python. The google search about reversible object does not yield anything more than the above threads. So, my question is, What does reversible object mean? How can I solve this issue? -
Bootstrap auto-complete on pycharm
I've been working on a Django project, I'm using Pycharm as my IDE, the problem is that , firstly I don't have a CSS file type in the new file section, also I don't have autocomplete for bootstrap so I have to write everything manually which really is a pain in the ass. Any help would be much appreciated. I'm using Pycharm community edition 2017 and i'm on Ubuntu 16.0.4. -
How do i display passwords fields on a registration form made by extending django user model?
I'm trying to create a custom django registration form which users can sign up from but i'm not sure how to go about letting the user set the password. I have tried extending the model by using OneToOneField but all i get on the templates are the usual username, email but no password fields?can someone help? from django import forms from django.contrib.auth.models import User from django.forms import ModelForm from administration.models import Agent, Post from django.contrib.auth.forms import UserCreationForm class userForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password1', 'password2'] class agentForm(forms.ModelForm): class Meta: model = Agent fields = ['bio','photo','phone','address','company','location'] class ContactForm(forms.Form): name = forms.CharField(max_length=150) email = forms.EmailField() subject = forms.CharField() message = forms.CharField(widget = forms.Textarea) -
CSS is not showing in the admin page -Django
So I upload my site to digitalocean and when I went to the admin page the CSS was not showing I visit all these sites but nothing seems to work Django doc-static files Pythonanywhere-DjangoStaticFiles StackOverflow -why my django admin site does not have the css style I set up my STATIC_ROOT and STATIC_URL, and then I ran python manage.py collectstatic And here is my seting STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/home/django/django_project/django_project/static') -
django get_all_permissions() return set([]) only set permission with user.user_permission.set([list of perm, ...])
If I set permissions in admin work and get_all_permissions() return a list of permissions but if I set permissions with user.user_permission.set([list_of_permissions, ...]) not work and i dont find how to make I am using python 3.5 and django 2.0.2 -
Django autocomplete light Creation of new choices
I installed autocomplete light and add the according to this tutorial : https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html models.py : class Stocks(models.Model): user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(blank=True,null=True,max_length=64,verbose_name=_('number')) suffix=models.CharField(blank=True,null=True,max_length=12,verbose_name=_('uffix')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) def __str__(self): return str(self.name)+ '-' +str(self.number) class Meta: verbose_name=_('Stock') verbose_name_plural=_('Stocks') def get_absolute_url(self): return reverse('BallbearingSite:mystocks' ) forms.py : class StocksForm(forms.ModelForm): name=forms.ModelChoiceField(queryset=Stocks.objects.values_list('name', flat=True).distinct(),label=_('name')) class Meta(): model=Stocks fields=('name','number','suffix','brand','comment','price') widgets = { 'name': autocomplete.ModelSelect2(url='country-autocomplete') } views.py: class StocksAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Stocks.objects.none() qs = Stocks.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs urls.py : url(r'^stock-autocomplete/$',views.StocksAutocomplete.as_view(create_field='name'),name='stock-autocomplete',), template.html : <form enctype="multipart/form-data" method="post" > {% csrf_token %} {{ stocks_form.as_p }} {{form.media }} {% block javascript %} <input id="savestocks" type="submit" name="" value="submit"> </form> <script type="text/javascript" src="{% static 'js/jquery-1.12.4.min.js' %}"> </script> <script type="text/javascript" src="{% static 'js/jquery-ui.min.js' %}"> </script> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery-ui.css' %}"> {% endblock %} it was written in tutorial to add (create_field='name') in url to be able to add new choice to autocomplete list but the autocomplete in my form is like a dropdownlist and i can not write anything in it . it is like this : -
Django Channels Live Chat: AttributeError: 'Message' object has no attribute 'as_dict'
I've been following this tutorial to implement a live chat system into my Django project. so far it has gone well and i've fixed any issues which have come up but this one stumped me. 2018-02-26 19:45:34,241 - ERROR - worker - Error processing message with consumer TestApp.consumers.ws_receive: Traceback (most recent call last): File "/home/.virtualenvs/blog/lib/python3.5/site-packages/channels/worker.py", line 46, in run consumer(message) File "/home/.virtualenvs/blog/lib/python3.5/site-packages/channels/sessions.py", line 57, in inner return func(message, *args, **kwargs) File "/home/blog_dev/TutorsTalk/TestApp/consumers.py", line 23, in ws_receive Group('chat-'+label).send({'text': json.dumps([m.as_dict()])}) AttributeError: 'Message' object has no attribute 'as_dict' This error seems to only come up when websocket data is being received which is why when i'm trying to send data it is saved to the database. This means that I can read the messages if I open it on another browser or refresh the page. I can also tell that my disconnect code works too because in the Django development console it is telling me when IPs are disconnecting from the websocket. As you can probably tell I am quite new to this. This is my code in consumers.py @channel_session def ws_receive(message): label = message.channel_session['room'] room = Room.objects.get(label=label) data = json.loads(message['text']) m = room.messages.create(handle=data['handle'], message=data['message']) Group('chat-'+label).send({'text': json.dumps([m.as_dict()])}) I have tried some things that … -
Predefined django groups with custom permissions
I know in advance what groups of users will be. During development we often reset db that is obvious. But i wondering where is the best place to put this information and when put it to database cause i don't want to do that every single time via django admin by hand. I figure out something like this: I have simple map of perms on the basis of which I'm putting needed info to database via function. GROUP_PERMISSION_MAP = { user_constants.GROUPS.ADMINISTRATORS: { Bet: ['add', 'change', 'delete'], Transaction: [], User: ['add', 'change'], Category: ['add', 'change', 'delete'], BetInfo: ['add', 'change', 'delete'], }, user_constants.GROUPS.REGULAR_USERS: { Bet: ['add'], Transaction: [], User: ['change'], Category: [], BetInfo: ['add', 'change', 'delete'], } } def assign_perms_to_group(group: Group, model: Model, permissions: List[str]): permission_codenames = ['{}_{}'.format(permission, model.__name__.lower()) for permission in permissions] group.permissions.add(*Permission.objects.filter(codename__in=permission_codenames)) What are the best practice and how it should be done? Especially my questions are: Where this predefined groups with permissions should live (maybe exists some better way)? What is the best way and time to put it to database ? -
Adding to model with OneToMany and updating existing entries.
I have a couple of Django model questions. I am running the following code as a Django manage extension, which I am new to. 1) I am not certain my "Location.objects.get(city=key)" is correct for OneToMany in my add_server_to_db function. I suspect this is incorrect? 2) How can I harden this so if this is executed twice, it will update existing Server entries vs. error out? Django Server Model: class Servers(models.Model): name = models.CharField(('name'), max_length=128) location = models.OneToOneField('locations.Location', on_delete=models.CASCADE) ip_address = models.CharField(('ip_address'), max_length=128) date = models.DateField(auto_now=True) Django Location Model: class Location(models.Model): city = models.CharField(('city'), max_length=10) geolocation = models.PointField(('location')) Function: def add_server_to_db(data_dict): print(data_dict) for key, val in data_dict.items(): loc = Location.objects.get(city=key) m = Server( location=loc, name=val['name'], ip_address=val['ip_address'], m.save() Thanks. -
Django - How to fix unique constraint fields
I'm making a hobby project and I've got the following model: from django.contrib.auth.models import User from django.db import models class Group(models.Model): name = models.CharField(blank=False, max_length=25) description = models.CharField(max_length=50, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) def __str__(self): return self.name class Meta: ordering = ('name', ) # my intention is that one user cannot have more than one group with the same name unique_together = ('name', 'user') I would like to make it possible for the user to create new groups by using this generic class based view. from django.urls import reverse_lazy from django.views import generic from groups.models import Group class GroupCreate(generic.CreateView): model = Group fields = [ 'name', 'description' ] success_url = reverse_lazy('ideas:list') template_name = 'groups/group_create.html' def form_valid(self, form): form.instance.user = self.request.user return super(GroupCreate, self).form_valid(form) As long as I don't try to make an error by sending an existing group's name, everything works fine. But if I send an existing group's name (same user!), I get the following error: IntegrityError at /groups/create UNIQUE constraint failed: groups_group.name, groups_group.user_id Why does it occur? How could I fix it or catch the error? I'm using Django 2.0.2 -
How do you execute a join on a foreign key in a nested for loops in Django?
I have two model classes, Part and Chapter shown below class Part(models.Model): title = models.CharField(max_length=200) # part_image = models.ImageField(upload_to=upload_location, # null=True, # blank=True, # width_field="width_field", # height_field="height_field", # verbose_name='Image',) summary = models.TextField() def __str__(self): return self.title class Chapter(models.Model): part = models.ForeignKey(Part, default=None, related_name='part', on_delete=models.CASCADE,) title = models.CharField(max_length=200) hw_link = models.CharField(max_length=200) data_link = models.CharField(max_length=200) code_link = models.CharField(max_length=200) def __str__(self): return self.title The idea is to have each part be its own section that contains the relevant chapters and links. I figured that I could do something similar to this but it isn't returning any of the chapters: {% if part_list %} {% for part in part_list %} <div class="panel panel-default"> <div class="panel-heading"><h1>{{ part.title }}</h1> <h3><small>{{ part.summary }}</small></h3> </div> <div class="panel-body"> {% for chapter in chapter_list %} {% if chapter.part == part.title %} <h3>{{ chapter.title}}</h3> <a href="{{ chapter.hw_link }}"><i class="fa fa-home" aria-hidden="true"><i class="fa fa-briefcase" aria-hidden="true"></i></i> - homework</a>&emsp;&emsp; <a href="{{ chapter.data_link }}"><i class="fa fa-shower" aria-hidden="true"></i><i class="fa fa-table" aria-hidden="true"></i> - clean data</a>&emsp;&emsp; <a href="{{ chapter.code_link }}"><i class="fa fa-free-code-camp" aria-hidden="true"></i><i class="fa fa-file-code-o" aria-hidden="true"></i> - hot code</a> {% endif%} {% endfor %} </div> </div> {% endfor %} {% else %} <p>Part is not working</p> {% endif %} -
custom user model and many to many permissions authentication and authorization django
I have a custom user model that I am building in Django. I'm pretty clear on how its going to work. I though have an interesting permisions scheme. I am trying to confrim if my thought process is correct. Each user can be part of many venues. Of each venue a user is a part of they may have a different permission. I have my user table and then I have a permissions table the permissions table is of the following: pk venueID UserID isclient isvenueviewer isvenueeventplanner isvenueadmin issuitsviewer issuitssuperuser the venue id can be null meaning that no all users will have venues attached to them. my thought is that a user first gets authenticated by the user table then that user object is checked by the permissions table for what permissions that user has. Of those permissions the one needed for the current view to be authorized is filtered through. And see if valid. am I spot on? Thank you hugs and kisses! -
Creating a checkbox in such way that a user gets updated
I am trying to create a way that a student can enroll to a teacher's course. I added a boolean field to my StudentData model and from there I added a many-to-many field to my Course model. Each of my course page is a generated slug page and there all students are listed. I want that near each student a checkbox will be shown. And if teacher selects more students and presses Enroll button, only those students can view the course. Now, the template conditionals I can do them myself, but I am stuck on updating data the right way using the checkbox. This is the boilerplate: class StudentDataForm(forms.ModelForm): enrolled = forms.BooleanField() def __init__(self): if self.checked: self.fields['enrolled'].initial = True class Meta: model = StudentData fields = ('enrolled', ) class StudentData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) student_ID = models.CharField(unique=True, max_length=14) notes = models.CharField(max_length=255, default=None, blank=True) enrolled = models.BooleanField(default=False) course = models.ManyToManyField('Course', default=None, blank=True) class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher1 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, verbose_name="Course Teacher", related_name='%(class)s_course_teacher') teacher2 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, null=True, verbose_name="Seminar Teacher", related_name='%(class)s_seminar_teacher') slug = … -
how to get node children and print them MPTT
I am pretty new to django and MPTT, I have categories and products in a tree it looks something like this: Category Product1 Category1 Product2 Category21 Category2 Product3 I want to print this tree like this, but I can only print categories, Here is my code: models: class Category(MPTTModel): name = models.CharField(max_length=50, blank=False, unique=True) is_active = models.BooleanField(default=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', db_index=True) class Meta: verbose_name_plural="Categories" def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50, blank=False, unique=True) price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=4) is_active = models.BooleanField(default=True) category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True, db_index=True) def __str__(self): return self.name my views.py def index(request): categories = Category.objects.get(pk=1).get_descendants(include_self=True) return render(request, 'menu/index.html', {"categories": categories}) my index.html {% load mptt_tags %} <ul> {% recursetree categories %} <li> {{ node.name }} {{ node.set_product }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> My question would be how could I print the same tree, categories with products, Products are leaves. -
JavaScript can't access variables from Django view via HTML
The error I see in my browser console says that 2 variables in my .js throw a Reference Error because they are undefined. This code used to work but now fails as such. I have some code which somehow used to work but now fails. Since replication is very impractical, I'd like to describe the problem and learn how to better troubleshoot it. I can print the data for those variables in the context_dict from views.py and see that the data is there and everything looks OK. Those variables are called module_progressjs and studtests. I can also print the data for those variables within the HTML and see it that way. Why is JavaScript not seeing them? The HTML code to make the context_dict variables available to JS appears valid: <script type="text/javascript"> var studtests = {{ studtests | safe }}; var studobjs = {{ studobjs | safe }}; var integrityjs = {{ integrityjs | safe }}; var studsumryjs = {{ studsumryjs | safe }}; var module_progressjs = {{ module_progressjs | safe }}; var modavg = {{ modavg | safe }}; var tiiavg = {{ tiiavg | safe }}; var tii_progressjs = {{tii_progressjs | safe}}; </script> Everything else appears to be … -
Accessing propertis of OneToOneFiled in the Same model
In the below example I'm trying to make default amount on the receipt the total method of related model bill. Django throws an error. Is there a way to do this? class Bill(models.Model): amount1 = models.DecimalField(max_digits = 11, decimal_places = 2, default=0) amount2 = models.DecimalField(max_digits = 11, decimal_places = 2, default=0) def total_amount(self): return (self.amount1+self.amount2) class Receipt(models.Model): bill = models.OneToOneField(Bill, on_delete=models.CASCADE) amount = models.DecimalField(max_digits = 11, decimal_places = 2, default=bill.total) -
Create separate scoreboard for each league in django
I'm creating a sports betting app as my first django project. My models are: class Bet(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) home_goals = models.IntegerField() away_goals = models.IntegerField() score = models.IntegerField(default=None, null=True) class League(models.Model): id = models.AutoField(primary_key=True, auto_created=True) name = models.CharField(max_length=50) code = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) admin = models.ForeignKey(User, on_delete=models.CASCADE) class UsersToLeagues(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) league = models.ForeignKey(League, on_delete=models.CASCADE) class Meta: unique_together = ('user', 'league') Each user can join multiple leagues. Now I would like to get separate leaderboards for each league. It should contain a list of users assigned to that league and sum of their scores. I was able to do get all data I need but in a very retarded way presented below: def league_standings(request, league_id): league = League.objects.get(pk=league_id) league_members = UsersToLeagues.objects.filter(league_id=league_id) league_members_users = User.objects.filter(id__in=[user.user_id for user in league_members]) ids = [] userbets = [] userscores = [] for player in league_members_users: ids.append(player.id) userbet = Bet.objects.filter(user_id=player.id) userbets.append(userbet) userscore = userbet.aggregate(Sum('score')) userscores.append(userscore) Please advice how to do it smart and properly. Thanks in advance! -
Django run thread/task with database access allways paralell to webserver
I want to build a Mqtt Client, which stores some data in my django database. This client should always run, when the webserver is running. What is the best way to run a thread with database access (django models) paralle to the webserver? If read about the django background task model, but I am not sure if its a good way. -
Not seeing expected database/user in Docker postgres:*
I am dockerizing an existing Django application, but am struggling with initializing a database and connecting. My db service starts up with the following config, which looks right to me: db: build: context: /Users/ben/Projects/project-falcon/project-falcon-containers dockerfile: Dockerfile-db-local environment: POSTGRES_DB: falcon_db POSTGRES_PASSWORD: falcon POSTGRES_USER: falcon ports: - 5432:5432/tcp restart: always At this point, I would expect the separate api container to be able to connect but instead I get django.db.utils.OperationalError: FATAL: role "advocate" does not exist the relevant settings file: from .dev import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_SERVICE'], 'PORT': os.environ['DB_PORT'] } } which is built in api and configured thus api: build: context: /Users/ben/Projects/falcon/falcon-backend dockerfile: Dockerfile depends_on: - db - redis environment: DB_NAME: falcon_db DB_PASS: falcon DB_PORT: '5432' DB_SERVICE: db DB_USER: falcon ports: - 8001:8001/tcp volumes: - /Users/ben/Projects/falcon/falcon-backend:/falcon:rw So based on the documentation for the postgres container I expected the POSTGRES_* variables to create the user/database Django expects to connect as/to. But the error message sure makes me think it did not. So based on the docs and the following question: How to create User/Database in script for Docker Postgres I tried the older method of specifying a specific .sql file … -
TimeField displayed as date
Im using Django framework to build a simple inventory management system. There is data in the database populated using the django admin. Now when i display the data on the website (front-end), there is a time field which is displaying the date, although i am beginning to learn django, I assume my models are wrong. Below i've attached my models.py and also the error on the actual site. Models.py # -*- coding: utf-8 -*- from future import unicode_literals import time from django.db import models class Cart(models.Model): def str(self): return self.CartColor CartColor = models.CharField(max_length=255) Quantity = models.CharField(max_length=5) class Initials(models.Model): def unicode(self): return self.Staff Staff = models.CharField(max_length=255) FirstName = models.CharField(max_length=255) LastName = models.CharField(max_length=255) class RTInfo(models.Model): def str(self): return str(self.TicketNo) TicketNo = models.CharField(max_length=10) # TickStamp = models.DateField(auto_now_add=True, blank=True) class Room(models.Model): def unicode(self): return self.Number Number = models.CharField(max_length=5) class TCCheckOut(models.Model): def str(self): return str(self.ReturnDate) ReturnDate = models.DateField(auto_now_add=True, blank=True) ReturnTime = models.TimeField(auto_now_add=True, blank=True, unique_for_date=True) OutQuantity = models.CharField(max_length=255) Staff = models.ForeignKey(Initials, on_delete=models.CASCADE) Number = models.ForeignKey(Room, on_delete=models.CASCADE) CartColor = models.ForeignKey(Cart, on_delete=models.CASCADE) TicketNo = models.ForeignKey(RTInfo, related_name="custom_user1_profile", on_delete=models.CASCADE) # TickStamp = models.ForeignKey(RTInfo,related_name="custom_pass2_profile", on_delete=models.CASCADE) class TCCheckIn(models.Model): def str(self): return str(self.Date) Date = models.DateField(auto_now_add=True, blank=True) Time = models.TimeField(auto_now_add=True, blank=True) Quantity = models.CharField(max_length=255) Staff = models.ForeignKey(Initials, on_delete=models.CASCADE) Number = models.ForeignKey(Room, on_delete=models.CASCADE) CartColor … -
Django won't connect to Redis Docker container
I've spent forever trying to connect my Django container to Redis while using Docker-Compose. After hours of changing Docker and Django configs and trying different ways to run everything, I finally figured out that Redis was broadcasting to the host. These were the errors I was getting each try: Error 111 connecting to 0.0.0.0:6379. Connection refused. Error 61 connecting to localhost:6379. Connection refused. Error 111 connecting to 127.0.0.1:6379. Connection refused. -
Auto Generated Admin Dashboard For Meteor.js
I was interested if the is a package which auto generates an admin dashboard for a meteor application. Something similar to the admin dashboard of django. It seems that there are two popular solutions: - https://github.com/yogiben/meteor-admin - https://github.com/gterrono/houston/ The first has a problematic package dependency, which changing it causes my app to break, and the second one is no longer maintained and also causes artifacts in the app. I am wondering if there is some other package, which I might have missed? If not, which alternative is recommended to manage users, and the app's collections? Thanks and best regards -
Serialize OneToMany relation into array in Django
Suppose I have some django models: class Restaurant(Model): name = CharField(max_length=200) class Food(Model): restaurant = ForeignKey(Restaurant, on_delete=CASCADE) name = CharField(max_length=200) One Restaurant can have multiple foods. And I want my json to look like this: [ { "name": "xxx", "food": [{"name": "xxx"}, {"name": "xxx"}, ...] }, ... ] I can use something like: restaurants = Restaurant.objects.all().values() for restaurant in restaurants: restaurant['food'] = Food.objects.filter(restaurant__id=restaurant['id']).values() But this loses some optimization in SQL level, as this is using application level loop. Is there a better way to do this?