Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: no module named <projectname> Django Heroku
Help PLEASE!!! Newbie trying to put Django on Heroku... ~8-( Am I supposed to list my app somewhere else???? I just know it some foolish oversight.... I am trying to set up a Django site on Heroku free tier. It works locally (using Sqlite3) and I got it working on Azure - but after following many howtos for this I cannot get it to work and have found no answers (that worked). I am not great with Git and am pretty new to Django - but I think I have followed all the tutorials guidance. Heroku was set up with the same name as used in Git and is correct in wsgi.py. I have the requirements.txt(below), .gitignore, Procfile (web: gunicorn animalproject.wsgi --log-file -), .env ('DATABASE_URL=sqlite:///db.sqlite3' - just for local and this is in .gitignore) , runtime.txt (python-3.7.10), django-heroku, and settings.py correct I thought... I did install Postgresql per various tutorials and it shows as correct in Heroku. I am trying to use dj-database-url.And I do have a .env file with DATABASE_URL= postgres://@ec2-54-87-34-201.compute-1.amazonaws.com:5432/ Settings.py is: import environ import django_heroku import dj_database_url ... env = environ.Env() # allows use of env("x") environ.Env.read_env() ... WSGI_APPLICATION = 'animalproject.wsgi.application' DATABASES = { 'default': { 'ENGINE': … -
Django server receives broken string data from Android Device that uses QR scanner(Keyboard input)
I am an Android App Developer. And the app read QR code using QR Scanner device and get Token(a string) from it. I send: B8EurXd5xq9OsvcpGW Server Log receives something like this: B8 Eur Xd5xq9 Osvcp G W Is there a way to show \n, \r or something like that? I replaced them with replace("\r", ""), replace("\n", "") but didn't work. -
Django get specific users profile
I have a implemented a feature in my blog app that allows you to click on a user and view their profile / posts. I want to display information from the users profile such as the bio and profile picture. I was able to successfully display the username but nothing else. To solve this issue I need to get the specific users profile but I am unsure of the proper way to do this Been playing around with a few methods but haven't had anything work and all of the solutions I have found online are about getting the current user views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) userBio = User.objects.get('bio') #not working return Post.objects.filter(author=user).order_by('-date_posted') models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.CharField(max_length=200, null=True) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile,self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) -
Edit permissions for Django Details View for api calls
I am very new to django and currently trying to generate api calls to localhost:8000/stateapi/id where id is an id for a single "State" object in a json (like 1, 2, etc). It is using token authentication by passing a username and password to the "get-token" endpoint and then using that token for calls to the stateapi endpoint. I mostly followed this tutorial https://scotch.io/tutorials/build-a-rest-api-with-django-a-test-driven-approach-part-2 and keep getting a "detail": "You do not have permission to perform this action." Here are the views where CreateView handles the "localhost:8000/stateapi" endpoint and DetailsView handles the localhost:8000/stateapi/id endpoint. class CreateView(generics.ListCreateAPIView): queryset = State.objects.all() serializer_class = StateSerializer permission_classes = (permissions.IsAuthenticated,IsOwner) def perform_create(self, serializer): """Save the post data when creating a new State.""" serializer.save(owner=self.request.user) class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This class handles the http GET, PUT and DELETE requests.""" queryset = State.objects.all() serializer_class = StateSerializer permission_classes = (permissions.IsAuthenticated,IsOwner) I can't seem to figure out why the authenticated user has permission to access information from CreateView but not DetailsView. Here is the permissions code: class IsOwner(BasePermission): """Custom permission class to allow only bucketlist owners to edit them.""" def has_object_permission(self, request, view, obj): # Our problem is that we do not have a owner property for the object """Return True if … -
Django: Display Count of Ratings in ListView
I just started learing django and I'm trying to display a Product with the Amount of Ratings it has in a ListView. But I fail to generate the expected output. models.py class Product(models.Model): name = models.CharField(max_length=200) description = models.TextField(max_length=255, default=None) author = models.ForeignKey(User, on_delete=models.CASCADE) class ProductRating(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_rating') user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.SmallIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) views.py class ProductListView(LoginRequiredMixin, ListView): model = Product def get_queryset(self): return Product.objects.annotate(avg_rating=Avg('product_rating__stars')).order_by('-avg_rating') def get_context_data(self, **kwargs): data = super(ProductListView, self).get_context_data(**kwargs) data['product_rating_count'] = Product.objects.annotate(Count('product_rating')) return data template {{ product.name }} {{ product.avg_rating }} {{ product_rating_count }} This displays the name and average-rating as expected but puts a Queryset containing all Products next to each single product like this: <QuerySet [<Product: testp1>, <Product: testp2>, <Product: testp3>, <Product: testp4>]> -
Django get count of foreign key records by grouping on source
I have two models, Media: class Media(models.Model): persons = models.ManyToManyField( Person, blank=True, related_name="media", help_text="Persons identified in the media", ) reviews = GenericRelation(Review, related_query_name="media") source = models.ForeignKey( Source, on_delete=models.SET_NULL, blank=True, null=True, related_name="media", help_text="Source for this media", ) Review: class Review(models.Model): """Represents a review made by an Account on an object """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() review_item = GenericForeignKey('content_type', 'object_id') reviewer = models.ForeignKey( Account, blank=True, null=True, on_delete=models.SET_NULL, help_text="Account of the reviewer", ) I need to group Media based on source and get count of source where there is no review exists. In other words I need count of each source with where there is no relation with reviews exists. Please advise. -
The problem is "method' object is not iterable. I am doing a small Django app
Here is the error when I go to employees page (employees is the model): TypeError at /employees/ 'method' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/employees/ Django Version: 3.2 Exception Type: TypeError Exception Value: 'method' object is not iterable Exception Location: C:\Users\USER\PycharmProjects\djangoProject\djangoProject\djangoProject\djangoProject\djangoProject\djangoProject1\health_recommender_final\venv\lib\site-packages\rest_framework\serializers.py, line 677, in to_representation Python Executable: C:\Users\USER\PycharmProjects\djangoProject\djangoProject\djangoProject\djangoProject\djangoProject\djangoProject1\health_recommender_final\venv\Scripts\python.exe Python Version: 3.9.4 Python Path: ['C:\\Users\\USER\\PycharmProjects\\djangoProject\\djangoProject\\djangoProject\\djangoProject\\djangoProject\\djangoProject1\\health_recommender_final', 'C:\\Users\\USER\\PycharmProjects\\djangoProject\\djangoProject\\djangoProject\\djangoProject\\djangoProject\\djangoProject1\\health_recommender_final', 'C:\\Program Files\\JetBrains\\PyCharm ' '2021.1.1\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\USER\\PycharmProjects\\djangoProject\\djangoProject\\djangoProject\\djangoProject\\djangoProject\\djangoProject1\\health_recommender_final\\venv', 'C:\\Users\\USER\\PycharmProjects\\djangoProject\\djangoProject\\djangoProject\\djangoProject\\djangoProject\\djangoProject1\\health_recommender_final\\venv\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2021.1.1\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Fri, 18 Jun 2021 01:49:34 +0000 My main files are serializers and models. from rest_framework import serializers from rest_framework import Person class PersonSerializer(serializers.ModelSerializer): class Meta: models = Person fields = '__all__' from django.db import models # Create your models here. from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Person(models.Model): EDUCATION_CHOICES = ( ('NA', 'NONE'), ('SSC', 'SSC'), ('HSC', 'HSC'), ('undergraduate', 'UNDERGRADUATE'), ('graduate', 'POSTGRADUATE'), ('Further Studies or PhD', 'FURTHER/PhD'), ) DIET = ( ('Vegetarian', 'VEG'), ('Omnivore', 'OMNI'), ('Fish', 'FISH'), ) EXERCISE = ( ('na', 'NA'), ('yes', 'YES'), ('no', 'NO'), ) name = models.CharField(max_length=250,default="") education_details = models.CharField(max_length=150, choices=EDUCATION_CHOICES, default='NA') diet = models.CharField(max_length=80, choices=DIET, default='VEG') exercise = models.CharField(max_length=80, choices=EXERCISE, default='NA') class Meta: ordering = ('-name',) @property def __str__(self): return self.name So what should I do … -
Creating a multi-file uploader with Django Foreign Key
I am trying to create a JobRequestFile form where you can upload multiple files involving a foreign key to my JobRequest model. However, when trying to save, it takes me to my JobRequest form and says these fields are required. my form: class Meta: model = JobRequestFile fields = [ 'file' ] widgets = { 'file': ClearableFileInput(attrs={'multiple': True}), } my view: class FileUpload(FormView): form_class = JobRequestFileForm template_name = 'jobrequest/upload.html' # Replace with your template. success_url = 'loggedIn' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file') if form.is_valid(): most_recent_jr = JobRequest.get.latest('requestDate') for f in files: JobRequestFile.object.create(jobRequest=most_recent_jr, file=f) return self.form_valid(form) else: return self.form_invalid(form) My template: <form action='.' method='POST' enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <input type='submit' value='Save' /> </form> -
Two OneToOneFields for the same table are not allowed in Django models
so I am trying to store the user's location coordinates in another table by linking it to the original using a OneToOneField. class Coordinates(models.Model): lat = models.FloatField() lng = models.FloatField() class Trip (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #Drivers Profile departure = models.CharField(max_length=200) departureCoord = models.OneToOneField(Coordinates, on_delete=models.PROTECT) arrival = models.CharField(max_length=200) arrivalCoord = models.OneToOneField(Coordinates, on_delete=models.PROTECT) date = models.DateField(validators=[inthe_future]) time = models.TimeField(default=datetime.now().time()) vacant_seats = models.PositiveIntegerField() vehicle_used = models.ForeignKey(Vehicle, on_delete=models.PROTECT) price_per_person = models.IntegerField() status = models.CharField(choices=STATUS, default='UPCOMING', max_length=10) def __str__ (self): return f"{self.user.first_name} - ({self.departure} => {self.arrival})" I have used an OneToOneField for both arrivalCoord and departureCoord since each row on the Coordinates table is going to uniquely link the departure and arrival of every Trip. So by still having a one-to-one relationship, is it possible for me to get the same thing done as when I try to run makemigrations I'm thrown with this error. ←[31;1mapp.Trip.departureCoord: (fields.E304) Reverse accessor for 'app.Trip.departureCoord' clashes with reverse accessor for 'app.Trip.arrivalCoord'. HINT: Add or change a related_name argument to the definition for 'app.Trip.departureCoord' or 'app.Trip.arrivalCoord'.←[0m ←[31;1mapp.Trip.departureCoord: (fields.E305) Reverse query name for 'app.Trip.departureCoord' clashes with reverse query name for 'app.Trip.arrivalCoord'. HINT: Add or change a related_name argument to the definition for 'app.Trip.departureCoord' or 'app.Trip.arrivalCoord'.←[0m I think there … -
Is there an easy way for someone completely naive to docker and web hosting to set up connectivity to their website?
I am very new to the whole development thing so I apologize for the simpleness of my question. I have been scouring the internet and reading articles and watching videos trying to to this docker/django combo I have going live. Everything I've looked at seems to be intended for people who know somewhat what they are doing. It's just not clicking for me reading the documentation and reading these articles. The leap to actually launching this kind of software is what's getting me. I tried AWS, DockerHub, and a few others. My goal is just to get this little Django app I have going so that I can connect to it from work in the web browser without having my laptop there. I want my coworkers to be able to use it as they are a bit technically illiterate and it really simplifies this one thing that they have to do semi-daily. I hope this is enough pertinent info, but let me know if not. I have two separate docker images. One for MariaDB and the other for Django. My docker-compose.yml version: "3.3" # container networks to set up networks: django_db_net: external: false # the containers to spin up services: … -
how separate python web application(django), wsgi(gunicorn), web server(nginx) at two ec2
i have one EC2 instance on AWS and it's has python web application(django), gunicorn(wsgi),nginx(webserver). i decide to separate it because of trafic. (for using auto scaling) No.1 EC2 : python web application No.2 EC2 : web server But, I don't know where wsgi should be... I know wsgi is an interface between python application and web server. but, it's not kind of web server.. so, where should i set wsgi(gunicorn) in ? No.1 EC2 or No.2 EC2? and why? plz help me kindly. -
Django Rest Framework specify that email must be unique
Here's a serializer for registering a user. class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user Here's the api view: class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, # "token": AuthToken.objects.create(user)[1] }) On the api view, if I try to pass in a name that is exactly the same as an existing name, it will say that it already exists. However, I can still make the emails the same which I don't want. Is there a way to get it so that I can also tell DRF that I would like the email to have to be unique as well? -
Sorting by category in Django
such a problem: I made a sidebar and there is a list of categories in it, you need to change def get_queryset in such a way that when you click on a category, all posts with this category are shown. I need to store public = True and .order_by ('- data') in def get_queryset views.py class CategoryFilterView(LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Post template_name = 'news.html' context_object_name = 'news' permission_required = ('news.view_post', 'news.view_category') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def get_queryset(self): return Post.objects.filter(public=True).order_by('-data') models.py class Category(models.Model): category_name = models.CharField(max_length=64, unique=True) subscribers = models.ManyToManyField(User, blank=True, null=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.category_name class Post(models.Model): PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='Автор поста') PostNews = 'PN' PostArticle = 'PA' # «статья» или «новость» POSITIONS = [ (PostArticle, 'Статья'), (PostNews, 'Новость'), ] postCategory = models.ManyToManyField(Category, verbose_name='Категория поста', through='PostCategory') title = models.CharField(max_length=50, verbose_name='Название') positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle, verbose_name='Тип поста') category_id = models.ForeignKey(Category, verbose_name='Категория', null=True, on_delete=models.CASCADE, related_name='category_id') data = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') data_update = models.DateTimeField(auto_now=True, verbose_name='Дата редактирования') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото', blank=True, default='/photos/def/1.jpg/') previewName = models.CharField(max_length=128, verbose_name='Превью поста') text = models.TextField(verbose_name='Текст поста') rating = models.SmallIntegerField(default=0, verbose_name='Рейтинг') public = models.BooleanField(default=True, verbose_name='Опубликовано') def like(self): self.rating +=1 self.save() def dislike(self): self.rating -=1 … -
React + DRF API not working when using other device
I have two applications: React frontend (via create-react-app) on localhost:3000 Django backend (mainly django-rest-framework) on localhost:8000 I use JWT for authentication but I don't think that matters in this case. Those two apps interact like this: React app has only two routes available to everyone: login page and register page After logging in, login page sends a request to generate JWT which is saved in localStorage From now on each request has a header with JWT in it - done with axios.interceptors So this is how I log in: async function loginUser(email: string, password: string) { try { const response = await axios.post("/api/token/", { email, password, }); setToken(response.data); return true; } catch (error) { return false; } } It works because I have a following setting specified in my package.json: "proxy": "http://localhost:8000" This is my authRequest function which returns axios object to communicate with the API in an authenticated mannner: const baseURL = "http://localhost:8000/api"; export const authRequest = () => { const axiosInstance = axios.create({ baseURL, timeout: 5000, headers: { Authorization: getAccessToken() ? `JWT ${getAccessToken()}` : null, "Content-Type": "application/json", accept: "application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept", }, }); return applyInterceptors(axiosInstance); }; The applyInterceptors function add some interceptors which … -
I want to load images faster without directly changing resolution of the image but with a script or some other css stuff
Size of the image is changed in the css but it loads in full hd which makes the process very long. Website is made in django. #resize { width: 213px; height: 120px; border-radius: 5%; } <img id="resize" src="https://cdn.discordapp.com/attachments/649975215685632060/838073807218016286/latest.png"> -
Python Django Email
Good day, I have a Django app that sends emails. I used a google app password for my EMAIL_HOST_PASSWORD, it works perfectly fine, but the from_email always set to my email which I used to create the app password instead of the email it gets from the form. How can I fix this, please? -
I get error 405 after submitting the django form
i try to combine DetailView and form, but when i try to submit the form i get a 405 error views.py class ReplyToVacancy(DetailView): model = Vacancy template_name = 'vacancies/vacancy.html' pk_url_kwarg = 'vacancy_id' context_object_name = 'vacancy' # form_class = 'CreateApplication' # success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CreateApplication return context html <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> -
How can I dynamically create multi-level hierarchical forms in Django?
I'm building an advanced search page for a scientific database using Django. The goal is to be able to allow some dynamically created sophisticated searches, joining groups of search terms with and & or. I got part-way there by following this example, which allows multiple terms anded together. It's basically a single group of search terms, dynamically created, that I can either and-together or or-together. E.g. <field1|field2> <is|is not|contains|doesn't contain> <search term> <-> <+> ...where <-> will remove a search term row and <+> will add a new row. But I would like the user to be able to either add another search term row, or add an and-group and an or-group, so that I'd have something like: <and-group|or-group> <-> <field1|field2> <is|is not|contains|doesn't contain> <search term> <-> <+term|+and-group|_or-group> A user could then add terms or groups. The result search might end up like: and-group compound is lysine or-group tissue is brain tissue is spleen feeding status is not fasted Thus the resulting filter would be like the following. Data.objects.filter(Q(compound="lysine") & (Q(tissue=brain) | Q(tissue="spleen")) & ~Q(feeding_status="fasted")) Note - I'm not necessarily asking how to get the filter expression below correct - it's just the dynamic hierarchical construction component that I'm trying … -
Adding values_list produces AttributeError
When I do something like: def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['sdnClearedDates'] = serializers.serialize('json', Profile.objects.filter(pk=object_id)) return super(ProfileAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) it returns a valid list of json data. But when I add a values_list('sdn_cleared_dates', flat=True) inside the Profile query like this: Profile.objects.values_list('sdn_cleared_dates', flat=True).filter(pk=object_id) It returns an AttributeError. Exception Value: 'list' object has no attribute '_meta' What am I doing wrong? -
Сhecking for groups in html django
I need to check if there is a user in the author group, if there is, then these buttons will: appear <a href="{% url 'news_update' el.id %}" class="btn btn-primary">Редактировать пост</a> <a href="{% url 'news_delete' el.id %}" class="btn btn-primary">Удалить пост</a> If not in this group they do not appear -
Enable my Kivy mobile app to use sockets (for real time messaging text and images) to/from a Django backend
I am just learning about sockets and am confused about what would best suit my needs. I am not worried about scaling - this is just a learning project for me. I have a working kivy - Django RESTful API going for user authentication. Now, I am trying to add real time exchange of text and images. What options should I consider for Django ? Thanks in advance. Dave -
Can migrate with models.DateTimeField() but SQL Error with models.TimeField()
I have a Django model that is not working properly. When I migrate the following, I don't get any errors and I get an id, question_text, and time column in my database: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) time = models.DateTimeField() def __str__(self): return self.question_text But if I change the models.DateTimeField() to models.TimeField(), I can successfuly run python3 manage.py makemigrations: Migrations for 'app': app/migrations/0001_initial.py - Create model Question But when I then try to run python3 manage.py migrate, I get the following error: Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: Applying app.0002_question_time...Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) DEFAULT '22:12:07.640513' NOT NULL' at line 1") The above exception was the direct cause of the following … -
'TypeError at /api/chunked_upload/ Unicode-objects must be encoded before hashing' errorwhen using botocore in Django project
I have hit a dead end with this problem. My code works perfectly in development but when I deploy my project and configure DigitalOcean Spaces & S3 bucket I get the following error when uploading media: TypeError at /api/chunked_upload/ Unicode-objects must be encoded before hashing I'm using django-chucked-uploads and it doesn't play well with Botocore I'm using Python 3.7 My code is taken from this demo: https://github.com/juliomalegria/django-chunked-upload-demo Any help will be massively helpful -
Aiottp + Aiohttp Swagger dosen't works
my application is Django + Aiohttp + Gunicorn (localhost) I started use aiohttp-swagger to documentation, but the files doesn't load (html, css and javascript). Can someone help me? The route /api/doc generate by aiohttp-swagger - net::ERR_ABORTED 500 (Internal Server Error) -
How to create a Parent/Child relationship with Django REST models?
I am new to Django REST and want to basically create a join table like this. One Page (txt doc) can have a parent and child Page. Each and every Page can be a parent and child of multiple other pages. Both the Page Entity and PageToPage Entity have an implemented model & serializer in the backend, where the serializer looks like this: class PageToPageSerializer(serializers.ModelSerializer): parent_page = PageSerializer(many=True, read_only=True) child_page = PageSerializer(many=True, read_only=True) class Meta: model = PageToPage fields = ['pkid', 'parent_page', 'child_page'] When entering the manage.py shell and create a PageToPage object, it just yields empty results: # Create Pages p1 = Page(title="Parent Page 1", text="Once upon a time, there was a young man...", page_of_user=u2) p1.save() p3 = Page(title="Child Page 1", text="Once upon a time, there was a young man...", page_of_user=u2) p3.save() # Create Page Relationships ptp = PageToPage(parent_page=p1, child_page=p3) ptp.save() # Select all Pages print("Created Pages:") ser2 = PageSerializer(Page.objects.all(), many=True) print(ser2.data) # Select all Page to Page relationships ser_ptp = PageToPageSerializer(PageToPage.objects.all()) print("Created Page relationships:") print(ser_ptp.data) Output: >>> Created Pages: >>> [OrderedDict([('pkid', 1), ('title', 'Test Page number 1'), ('text', 'Just some sample text'), ('creation_date', '17.06.2021'), ('page_of_user', UUID('eeec0437-75f2-44ba-935d-96fcb78e38c6'))]), ...] >>> Created Page relationships: >>> {} What am I doing wrong? …