Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I query objects of all children and their chield with Django mptt?
I have created a model but when i am trying to access all child and also their child. parent child 1 child 1-1 child 2 child 2-1 Is there way to get all child node. I am doing like this but not able to all child. 1st Query query_set = Category.objects.get(name='parent').get_family().order_by('tree_id', 'lft') 2nd Query query_set = Category.objects.get(name='parent').get_descendants().order_by('tree_id', 'lft') But I am unable to get all object that is associate with parent and their child. I need record should be [child 1, child 1-1, child 2, child 2-1] -
Django users created through proxy can't login
I created a model inheriting from django.contrib.auth.models.User, and extended it with more fields, and then created a proxy that overrides save() method to hash the password, but users created through this proxy can't login. I traced the process and found that user.check_password() always fails, but I don't know the reason. This is my model and its proxy: class UserExtended(User): albums = models.ManyToManyField(Album, null=True, blank=True, verbose_name='Albums') class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return "[{}] {} ({})({}{})".format(self.id, self.email, self.username, self.first_name, self.last_name) class UserExtendedProxy(UserExtended): class Meta: proxy = True def save(self, *args, **kwargs): if not self.id: try: user = User.objects.get(email=self.email) except: pass else: raise Exception('eMail already in use.') self.set_password(self.password) super(UserExtendedProxy, self).save(*args, **kwargs) Token.objects.create(user=self) And this is my ModelBackend: class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwars): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None I can see in my database that users created through this proxy actually exist in *django.contrib.auth.models.User** model, so I can't figure out why they can't log in. Another issue is that superuser created through python manage.py createsuperuser doesn't exist for UserExtendedProxy. -
How to return data from nested serializers inside serializers built on the fly?
Recently I have been trying out new things with Django, to try and simplify writing responses in the views, might not be worth doing in the end, but I'm still interested to see if it can be done. So typically, we would have the following serializer for returning back information; # serializers.py class SomeDefinedSerializer(serializers.ModelSerializer): extra_model = SomeExtraModelSerializer() greet_name = serializers.SerializerMethodField() class Meta: model = SomeDefinedModel fields = ('name', 'age', 'field1', 'field2') def get_greet_name(self, obj): return f"Hello {obj.name}" Now with this defined serializer, we can return just the fields we want, and then assumming in SomeExtraModelSerializer() we have defined a subset of fields, we get back a nice dictionary of values with calling .data. But doing this, with large-scale apps, we will end up writing loads and loads of serializers that just get used for specific tasks, resulting in a lot of code that is almost virtual similar. Of course, we dont HAVE to do it this way, we could make more general serializers, but that means that all the different tasks from the frontend end up getting a huge surplus of information, that in reality only a small percentage of the data gets used. So my original thought was to … -
How to send data back to Android app from django rest framework using asynchttp?
Model.py class Server(models.Model): label = models.TextField(max_length=200,null=True) #compare this upload1 = models.FileField(null=True, blank=True) Image1 = models.TextField(upload1, null=True) class Android(models.Model): label=models.TextField(max_length=200,null=True) #with this imagestring=models.TextField(null=True,blank=True) returnlabel=models.TextField(null=True,blank=True) So in my serializer class i am comparing labels from Android model and server model in (def get_returnlabel),and i want to return this label back to my android app.Any suggestons on how to do it.On my android app I am using async http. Serializer.py class FoodSerializers(serializers.HyperlinkedModelSerializer): class Meta: model=Server fields=('url','label','Image1','upload1') class AndroidSerializers(serializers.ModelSerializer): class Meta: model = Android fields = ('label', 'imagestring', 'returnlabel') (<--returnlabel back to android app) #Compare label from Server and Android def get_return_label(self, obj): queryset = Server.objects.filter( labelServer=obj.label) queryset_serializer = FoodSerializers( queryset, many=True, read_only=True) return queryset_serializer.data Views.py class FoodViewSet(viewsets.ModelViewSet): queryset = Server.objects.all() serializer_class =FoodSerializers class Androids(viewsets.ModelViewSet): queryset =Android.objects.all() serializer_class = AndroidSerializers -
Dynamic django model
I have ProjectCategoryCountPartition model. And 3 classmethod to create partition model. class ProjectCategoryCountPartition(models.Model): city_slug = models.CharField(verbose_name=_('City slug'), max_length=255, db_index=True) domain = models.CharField(verbose_name=_('Site name'), max_length=255) category_id = models.PositiveIntegerField(verbose_name=_('Category id')) name = models.CharField(verbose_name=_('Category project name'), max_length=255) count = models.PositiveIntegerField(default=0) class Meta: db_table = "wbtm_projects_category_partition" class DefaultMeta: db_table = "wbtm_projects_category_partition" ATTRIBUTE = { 'city_slug': models.CharField(verbose_name=_('City slug'), max_length=255, db_index=True), 'domain': models.CharField(verbose_name=_('Site name'), max_length=255), 'category_id': models.PositiveIntegerField(verbose_name=_('Category id')), 'name': models.CharField(verbose_name=_('Category project name'), max_length=255), 'count': models.PositiveIntegerField(default=0) } @classmethod def check_partition(cls, city_slug): city_slug = cls.check_city_slug(city_slug) default_db_table = cls.DefaultMeta.db_table new_db_table = "{}_{}".format(default_db_table, city_slug) if new_db_table in connection.introspection.table_names(): return True return False @classmethod def check_city_slug(cls, city_slug): city_slug = city_slug.replace('-', '_') if not re.match('^[a-zA-Z0-9_]+?$', city_slug): raise Exception('Unsupported city_slug') return city_slug @classmethod def create_partition(cls, city_slug): city_slug = cls.check_city_slug(city_slug) default_db_table = cls.DefaultMeta.db_table new_db_table = "{}_{}".format(default_db_table, city_slug) if cls.check_partition(city_slug): return new_db_table queries = [ """ CREATE TABLE {}() INHERITS ({}); """.format(new_db_table, default_db_table), ] cursor = connection.cursor() for query in queries: cursor.execute(query) return new_db_table @classmethod def get_city_model(cls, city_slug): city_slug = cls.check_city_slug(city_slug) model_name = city_slug.replace('_','') db_table = cls.create_partition(city_slug) attrs = cls.DefaultMeta.ATTRIBUTE.copy() attrs.update({ '__module__': ProjectCategoryCountPartition.__module__, 'Meta': type( 'Meta', (), dict( # managed=False, db_table=db_table, ) ), }) return type("ProjectCategoryCountPartition{}".format(model_name), (models.Model,), attrs) When I use for an error occurs. The model apparently starts caching in memory or the fields … -
In Django REST Framework, why do serializers properly handle field-level validation exceptions in models but not object-level validation?
To illustrate my problem, let's say I have a simple Person model defined like this: from django.db import models from django.core.validators import MinLengthValidator, MaxLengthValidator, ValidationError class Person(models.Model): first_name = models.CharField(max_length=100, null=False, blank=False, validators=[MinLengthValidator(limit_value=1), MaxLengthValidator(limit_value=100)]) last_name = models.CharField(max_length=100, null=True, blank=True, validators=[MinLengthValidator(limit_value=1), MaxLengthValidator(limit_value=100)]) def clean(self): self.validate() super().clean() def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) def validate(self): """The first and last names cannot be the same strings.""" if (self.first_name and self.last_name and self.first_name.lower() == self.last_name.lower()): raise ValidationError('First and last names, if both are provided, cannot be the same.', code='invalid', params={'first_name': self.first_name, 'last_name': self.last_name}) Notice that both the first_name and last_name fields have field-level validation associated with them. (My dev database is SQLite, and it does not do length validation. So I had to add validators. But that is not my question.) I defined two simple APIView-based classes: from rest_framework import generics from ..models import Person from ..serializers import PersonSerializer class PersonDetailView(generics.RetrieveUpdateDestroyAPIView): name = 'person-detail' queryset = Person.objects.all() serializer_class = PersonSerializer lookup_field = 'id' class PersonListView(generics.ListCreateAPIView): name = 'person-list' queryset = Person.objects.all() serializer_class = PersonSerializer lookup_field = 'id' I defined a serializer based on Django REST Framework's ModelSerializer: from rest_framework import serializers from ..models import Person class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields … -
Incorrect schema in DRF documentation for custom ViewSet action
I have such ViewSet: class CarViewSet(ModelViewSet): """ Работа пользователя с его машинами. """ serializer_class = CarSerializer permission_classes = [IsUser] filter_fields = '__all__' ordering_fields = '__all__' def perform_create(self, serializer): serializer.save(user=self.request.user.useraccount) def get_queryset(self): return Car.objects.filter(user=self.request.user) @action(methods=['POST'], detail=True) def set_default(self, request, pk=None): """ Установить указанную машину по умолчанию """ car = get_object_or_404(self.get_queryset(), pk=pk) car.is_default = True car.save() return Response() And in rest_framework.documentation page I see such form for a "set_default" action: The problem is "set_default" actually don't need to provide all of these fields, it requires(and uses) only id! What can I do with this? -
vuejs + drf - unable to get data from drf api in vuejs using http/axios
enter image description here Unable to get data in Vue js from drf api using http / axios ? I am not getting any error also -
Spotify API {'error': 'invalid_client'} Authorization Code Flow [400]
This is one of my many attempts at making a POST request to https://accounts.spotify.com/api/token. Scope was set to 'playlist-modify-public, playlist-modify-private'. I'm using Python 3.7, Django 2.1.3. No matter what I do, response_data returns {'error': 'invalid_client'} I've tried many things, including passing the client_id/client_secret inside the body of the request as per the official Spotify documentation for this particular request... to no avail. Please help! def callback(request): auth_token = request.GET.get('code') # from the URL after user has clicked accept code_payload = { 'grant_type': 'authorization_code', 'code': str(auth_token), 'redirect_uri': REDIRECT_URI, } auth_str = '{}:{}'.format(CLIENT_ID, CLIENT_SECRET) b64_auth_str = base64.b64encode(auth_str.encode()).decode() headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic {}'.format(b64_auth_str) } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers) response_data = json.loads(post_request.text) # ==> {'error': 'invalid_client'} -
Django and Celery to send requests to external API "remote end closed"
To collect data into my Postgres database I run a collection of requests to an external API every 10 minutes or so. This system has worked without a hitch for a few weeks but now about half of the requests timeout with the error: raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) I can't really share much of the code as it is sensitive but I can share the vague structure of it. def getData(): for thing in things: response = requests.request("POST", url, data=payload, headers=headers) and then getData() is run every 10 minutes by Celery. I would say the size of things is roughly 100 elements and typically it would finish in 50 seconds. -
Django - Return empty value from select tag of html
There's a form for students to register . Each of the students are in a school. And by using forms.ModelChoiceField the name of schools will be shown in the template using a 'select' tag. ( a dropdown list ) The main problem is, After choosing one 'option' of the 'select' tag , I can't get the select's value in views.py . models.py class School(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=40) school = models.ForeignKey(School) def __str__(self): return self.name forms.py class SchoolForm(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.name class StudentForm(forms.ModelForm): student_school = SchoolForm(queryset = School.objects.all()) class Meta: model = Student fields = ('name', 'school') views.py def student_register(request): if request.method == 'POST': form = StudentForm(request.POST) form.school = request.POST['school'] if form.is_valid(): form.save else: form = StudentForm() return render(request, 'index.html', {'form': form}) index.html <form method="post" action={% 'student_register' %}> {% csrf_token %} {{ form.name }} <select id="id_school" name="school"> {% for name in form.student_school %} <option value={{ name }}> {% endfor %} </select> </form> -
Saving data in rows in a Config table vs. saving as keys in a Postgres JSONField--which is better?
Since Postgres supports JSON fields, is that more preferential than say saving each config item in a row in some table the way WP still does? Full disclosure: I'm asking as a Django user new to postgres. -
I get a 'Forced update did not affect any rows' error when overriding save() method of Django Model
I have a model and a corresponding proxy: class UserExtended(User): albums = models.ManyToManyField(Album, null=True, blank=True, verbose_name='Albums') class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return "[{}] {} ({})({}{})".format(self.id, self.email, self.username, self.first_name, self.last_name) class UserExtendedProxy(models.UserExtended): class Meta: proxy = True def save(self, *args, **kwargs): from django.contrib.auth.hashers import make_password if not self.id: try: user = User.objects.get(email=self.email) except: pass else: raise Exception('eMail already in use.') self.password = make_password(self.password) super(UserExtendedProxy, self).save(args, kwargs) I think my logic is flawed because I get a Forced update did not affect any rows error when creating a new instance, but I can't find what causes the error. -
Cart in bootstrap navbar disappears after login
The cart icon on my navbar diasappears once the user logs in. I have tried to debug it but i cannot figure it out. What am I doing wrong? Do I need to authenticate the user similar to the login icon in the toolbar? <ul class="navbar-nav ml-auto"> {% if user.is_authenticated %} <li {% if 'dashboard' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'profile' %}"> Welcome {{ user.username }}</a> </li> <li class="nav-item mr-3"> <a href="javascript:{document.getElementById('logout').submit()}" class="nav-link"> <i class="fas fa-sign-out-alt"></i> Logout </a> <form action="{% url 'logout' %}" method="POST" id="logout"> {% csrf_token %} <input type="hidden"> </form> </li> {% else %} <li {% if 'register' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'register' %}"> <i class="fas fa-user-plus"></i> Register</a> </li> <li {% if 'login' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'login' %}"> <i class="fas fa-sign-in-alt"></i> Login</a> <li {% if 'cart' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'cart' %}"> <i class="fas fa-cart-plus"></i> Cart</a> </li> Before I … -
Object of objects JSON response from Django backend to React-Redux frontend
This is the response from Django when making axios api call in the frontend (array of objects). [ { "id": 1, "title": "How to create a django-react app", "body": "You should first do this stuff and that" }, { "id": 2, "title": "How to connect django with react", "body": "Get this and that stuff" } ] But this is the response that I want (object of objects). { 1: { "id": 1, "title": "How to create a django-react app", "body": "You should first do this stuff and that" }, 5: { "id": 5, "title": "How to connect django with react", "body": "Get this and that stuff" } } serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' views.py class ArticleViewSet(ViewSet): queryset = Article.objects.all() def list(self, request): serializer = ArticleSerializer(ArticleViewSet.queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): article = get_object_or_404(ArticleViewSet.queryset, pk=pk) serializer = ArticleSerializer(article, many=False) return Response(serializer.data) -
Using same models for different webpages
So I have a Topic. class Topic(models.Model): text = models.CharField(max_length = 200) date_added = models.DateTimeField(auto_now_add = True) owner = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete = models.CASCADE) text = models.TextField(blank = True, null = True) date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = 'entries' def __str__(self): The topic is retrieved and displayed based on the date it was created. def topics(request): """Show all topics """ topics = Topic.objects.order_by('date_added') context = {'topics' : topics} return render(request, 'learning_logs/topics.html', context) What I would like to do is to have the Topic somehow distinguished based on which web page it was created from. And then I want the same topic to be displayed on the same webpage. As you can see here, below. The same topic is displayed on topic.html and f_topic.html because the same topic_id is used. I want to have it so that if the topic was created on topic.html then it is displayed on topic.html. If it is created on f_topic.html then it is displayed on f_topic.html. def topic(request, topic_id): topic = Topic.objects.get(id = topic_id) entries = topic.entry_set.order_by('-date_added') images = Image.objects.filter(imgtopic__in = entries) context = {'topic': topic, 'entries': entries, 'images': images} return … -
How to connect to user specified Postgres database on Django and Heroku?
I have a web app in Django that uses a Postgres database for everything in the app. Everything is working great with this connection as expected and the app is working totally fine. A feature of the app is to allow users to connect to and query data from their own Postgres database. The requirement is for the user to provide their credentials and for the app to connect and query certain data. This feature is working as expected locally using psycopg2 as the Postgres driver and has been tested with multiple external Postgres databases (i.e. databases other than the one the app is using). The resulting query is returned within 1-5 seconds. However, when deployed on Heroku and tested with the same databases, the connection never gets established and the request times out. I tried using Celery and background processes but the connection still never gets established. What is needed to create this connection and query databases? Are there any other libraries that I need to install on Heroku other than psycopg2. The code that creates the connection is as follows, and again works totally fine locally: cnx = psycopg2.connect(host=request_body['hostname'], database=request_body['dbname'], user=request_body['username'], password=request_body['password'], port=request_body['port']) Please advise. Thanks! -
Graphene and Django about relationships
I'm very new to Graphene and testing it to see if i could use it for a Django project with complex queries. To test it, i'm trying to create an Ecommerce with the following models class Sku(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) class ProductSku(models.Model): sku = models.ForeignKey(Sku, related_name='product_sku', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='product_sku', on_delete=models.CASCADE) price = models.IntegerField() As you can see here Product and Sku have a many to many relationship using the model ProductSku Using the documentation from Graphene i created the following Schema class SkuNode(DjangoObjectType): class Meta: model = Sku class ProductNode(DjangoObjectType): class Meta: model = Product class ProductSkuNode(DjangoObjectType): class Meta: model = ProductSku class Query(graphene.ObjectType): all_products = graphene.List(ProductNode, name=graphene.String()) product = graphene.Field(ProductNode, id=graphene.Int()) def resolve_all_products(self, info, **args): name = args.get('name') if name is not None: return Product.objects.filter(name__icontains=name) return Product.objects.all() def resolve_product(self, info, **args): id = args.get('id') if id is not None: return Product.objects.filter(pk=id).first() Right now my frontend app could get the price of a given product for a given sku by doing a query that asks for query{ allProducts{ id, name, productSku{ price, sku{ id, name } } } } But what i want to do is a query that asks for the price … -
SQL query generated by django F expression
Does anyone know the actual query generated by django when you use F expression? What will the generated query be for the example mentioned in the doc: https://docs.djangoproject.com/en/2.1/ref/models/expressions/#f-expressions from django.db.models import F reporter = Reporters.objects.get(name='Tintin') reporter.stories_filed = F('stories_filed') + 1 reporter.save() I tried viewing the query generated using: from django.db import connection logging.info('[----- DEBUG -----] Query -1: %s', connection.queries[-1]) logging.info('[----- DEBUG -----] Query -2: %s', connection.queries[-2]) logging.info('[----- DEBUG -----] Query -3: %s', connection.queries[-3]) but I don't see any query on the my model/table. Anyone know how to figure this out? -
How do i setup elasticcache redis for channel layer in django?
currently i have 2 servers both of them have redis address in common and the code i have is as below.and i am using AWS ElasticCache service CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { 'hosts': ['redis://location:6379'], }, 'ROUTING': 'app.routing.channel_routing', } } issue is one connects and another server throws 502 error -
How to make a table in report lab pdf to print on the next page when it reaches the end of page size
I have a table in report lab in django that i want it to continue printing its values on the next page when it reaches the end of A4 page. Is their any way to keep track on the current position when printing? And what does t.wrapOn and t.drawOn mean? My Django code: buffer = io.BytesIO() p = canvas.Canvas(buffer) width, height = A4 data = [ ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ] t = Table(data, style=[ # ('GRID', (0, 0), (-1, -1), 0.5, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.blue), # ('VALIGN', (3, 0), (3, 0), 'BOTTOM'), # ('ALIGN', (3, 1), (3, 1), 'CENTER'), # ('ALIGN', (3, 2), (3, … -
A bug while inserting a serializer in the raw data section, Django REST Framework
Showing below is a product (with id 65) containing two categories (with id 1 and id 66), the bug is that I didn't add the category of id 1 when creating the product I only added the category of id 66 ( in the 'Raw Data' section) , so each time I add a new product with a category inside , the category of id 1 gets added automatically to the list of categories. That's the bug ! { "id": 65, "product_code": "kdhjkfh", "name": "klfjkj", "quantity": 12, "price": 12, "categories": [ { "id": 1, "name": "ksjdf", "products": [ 65 ], "categories": [ 4 ] }, { "id": 66, "name": "dkllj", "products": [ 65 ], "categories": [] } ] } the serializers.py part of the product class ProductSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True, required=False) class Meta: model = Product fields = ('id', "product_code", "name", "quantity", "price", 'categories') def create(self, validated_data): category_data = validated_data.pop('categories') product = Product.objects.create(**validated_data) dicti={} for items in category_data: for key, value in items.items() : dicti[key] = value if 'id' in dicti: x= product.categories.get_or_create(id = dicti['id']) product.categories.set(x) return product Does anybody has any idea why the category of id 1 gets added automatically ? -
how to solve sidebar is messed up in mobile view django app
I have a website, which contains navigation bar and side bar. Navigation bar is automatically translate into mobile view , but sidebar is messed up. what can i do with this? what solutions do I have? looks like this PC view sidebar went to the background here in mobile view -
General Django Rest Question on Serializers
Quick concept question for you. I am working through a Django tutorial that involves building an api backend via django(using v 2.1). I have the following serializer for handling Comment objects from my Comment model in my articles app. class CommentSerializer(serializers.ModelSerializer): author = ProfileSerializer(required=False) createdAt = serializers.SerializerMethodField(method_name='get_created_at') updatedAt = serializers.SerializerMethodField(method_name='get_updated_at') class Meta: model = Comment fields = ( 'id', 'author', 'body', 'createdAt', 'updatedAt', ) def create(self, validated_data): article = self.context['article'] author = self.context['author'] return Comment.objects.create( author=author, article=article, **validated_data ) I want better understand this section of code: def create(self, validated_data): article = self.context['article'] author = self.context['author'] Specifically where is 'context' coming from? I have enough of an understanding of what exactly is going on here, I am more or less just curious of the mechanics behind what's going on here. For instance we didn't state context as an argument variable in the create function. Is context coming from my model? Is there some django magic taking place in the rest_framework that is assigning (maybe the entire instance) the context variable? Thanks everyone! -
How to link two objects saved in different places in Django
I am trying to achieve something similar to what Facebook is doing: in a blog post, when we you post a link to an article, it automatically fetches the tag to get the image, title and description, and render it on the page. When drafting the post, I use a websocket thanks to Django Channels to send the link from the front to the backend to retrieve the different elements via Beautiful Soup. And then I send them back to the front to display them. The issue arises when I want to save the post along with the shared url elements. To manage the post creation, I use a CBV PostCreate. I can save the shared url elements in the consumer. But the two objects are not linked and I don't know how to get the SharedArticle object id and save it with the post. I have two models: Post and SharedArticle. Here is my consumer.py class UrlConsumer(AsyncConsumer): async def websocket_connect(self, event): chat_room = "shared_url" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("receive", event) page = urlopen(event['text']) soup = BeautifulSoup(page, "html.parser") title = soup.find('meta', property='og:title') img = soup.find('meta', property='og:image') description …