Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a django app that runs inside a docker container use the host's sendmail service
I am supposed to do a demo where I am required to deploy using docker on a server machine that has been provided to me which already has sendmail set up on it. So if I ssh and run echo "Subject: sendmail test" | sendmail -v <my_email>@gmail.com I actually receive an email, it works. The above command also works if I enter the container and run it from its shell. So, the container can communicate with the host's sendmail fine. Now my problem is that I am not sure how should I make my django application, that runs in the container, use the host's sendmail in order to send some emails. I have read this question which is similar to my problem. I tried the first suggestion, that is to use localhost as the EMAIL_HOST but I don't receive any emails. I tried setting the EMAIL_HOST_USER=localhost , without a password, but I am getting an error smtplib.SMTPException: STARTTLS extension not supported by server. which, from what I read, means that I do not need to login I would like to avoid adding the suggested package mentioned in the answer, since in a production deployment they will probably not be using … -
django, multi-databases (writer, read-reploicas) and a sync issue
So... in response to an API call I do: i = CertainObject(paramA=1, paramB=2) i.save() now my writer database has a new record. Processing can take a bit and I do not wish to hold off my response to the API caller, so the next line I am transferring the object ID to an async job using Celery: run_async_job.delay(i.id) right away, or a few secs away depending on the queue run_async_job tried to load up the record from the database with that ID provided. It's a gamble. Sometimes it works, sometimes doesn't depending whether the read replicas updated or not. Is there pattern to guarantee success and not having to "sleep" for a few seconds before reading or hope for good luck? Thanks. -
PUT Request with React frontend and Django backend
I am trying to render API-data from my backend with a PUT-Request but I am getting an PUT http://127.0.0.1:8000/article/3/ 404 (Not Found) with an empty array which is saying: {id: Array(1)} id: Array(1)0: "This field is required." My code is working properly on a dummy API. My guess this error occurs it's because I am trying to render data on localhost. The PUT-Request on my Django backend also works fine. Do someone know why this is happening ? -
how can I move between pages without losing the searching? and How I keep the values of inputs when a search is a trigger?
when I get the objects when I do a search the pagination works perfect and also, the search do the search but when I navigate a page to another one the search result disappear hence force, the result of searches disappear I tried something like that: <a href="?{% for k, v in request.GET %}{{ k }}={{ v }}{% endfor %}&page_number=1">&laquo; first</a> but it doesn't work too. How can I fix this problem? also, when I submit to do a search the value of input disappears whether that exists in input search or any of filter input so, how can I keep the value of inputs until if I do the navigation for pages. my codes: .HTML page <!-- Pagination --> <div class="pagination-bar text-center"> <div class="container"> <span class="step-links"> {% if sentences.has_previous %} <a href="?{{ request.GET }}&page_number={{ sentences.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ sentences.number }} of {{ sentences.paginator.num_pages }}. </span> {% if sentences.has_next %} <a href="?{{ request.GET }}&page_number={{ sentences.next_page_number }}">next</a> <a href="?{{ request.GET }}&page_number={{ sentences.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> views.py def search(request): sentence = None word = None filtering = filters(request) actor = "" if request.method == "GET": # the query name of search formsets … -
My "cart" cookie in the request passed to my Django view is empty despite it showing in browser storage
I have a store page on my site (written in Django w/ a Passenger server) where users can add products to their shopping cart. The cart is stored as a cookie. When they proceed from the store page to the cart page, the cart view should list all of the items in their cart (which it gets from the cart cookie in the request). This works fine when I run it locally. However, when I run this in production, it almost always says the cart is empty. It only lists the cart items properly if I do a hard refresh of the page. I've added some print statements to the server, and I can see that the view for the page is being called twice in prod (it's only called once in dev). The first time the view is called, the cart cookie has the correct values. The second time it's called however, the cart cookie in the request is an empty object {}. All other cookies in the request look normal (session id, csrftoken, etc). What's very strange is I can see in the browser's developer panel that the cart cookie is populated in both the request's header cookie … -
Website responds to IP, but not to Domain
I'm new to all of this, I only started to learn how to code with python back in May 2020 and before then I had zero programming experience. I have hosted a Django-based website, which is running on Apache, on an AWS Lightsail Ubuntu 20.04 instance. The website is accessible when you use the ip, 18.133.43.205. But when I try to search my website using the domain, roosta.xyz, the connection times out. The DNS is using AWS's nameservers. I don't believe that the DNS is the problem as when I do a whois look up, it shows the AWS nameservers and when I run dig roosta.xyz in the linux terminal the correct ip is returned. Early today, I was getting a response from my server but it was requesting to use https, but I don't have a ssl certificate so my browser freaked out. I don't want to use https. But after meddling with the server, trying to stop it wanting to use https, I'm now back to the connection just timing out. One thing I found strange, is that when I run apachectl -S in the server terminal, it throws an AH00558 error because it's using the ip 3.9.114.166, … -
Using Django to authenticate user from Flask
How would you access the Django authentication framework from a Flask app? I have a Django app and Flask app running in parallel on a server. Both are hosted behind the same domain, but behind different paths, so they should be able to see each other's cookies. I'm using Flask to run a simple API microservice, where using Django would be overkill. However, to prevent abuse, I still want Flask to check the request's cookies to see if they're from a user who's still authenticated in the Django application. I don't want to re-implement an authentication framework in Flask. Access Django settings from inside Flask is relatively simple. I just put something like this at the top of my Flask script to set the path to my Django settings module: sys.path.insert(0, <path to Django project>) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangoproject.settings") from django.conf import settings However, I'm unsure how to update a Flask request handler to pull the correct cookies from a request and verify them with Django's authentication backend. How would I do this? -
How to limit the max deep of recursetree in Django mttp?
I'm using django-mttp,I have a question: How can I limit the max depth of recursetree? Max=3 class Comment(MPTTModel): """ 评论表 """ nid = models.AutoField(primary_key=True) news = models.ForeignKey(verbose_name='评论文章', to='News',to_field='id',on_delete=models.CASCADE) user = models.ForeignKey(verbose_name='评论者', to='User',to_field='id',on_delete=models.CASCADE) content = models.CharField(verbose_name='评论内容', max_length=255) create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['create_time'] <ul> {% recursetree comments_list %} <li> {{ node.content }} {{ node.level }} {% if node.parent %} <div>{{node.user}} 回复 {{node.parent.user}}</div> {% endif %} <button class="button" onclick="myFunction({{node.id}})"> Reply </button> {% if not node.is_leaf_node %} <ul class="children list-item"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> -
How to send email with gmail in Django Heroku without using any addon like SendGrid?
Just curious to know if there is any way to send email in Django heroku without using any addon. As sometimes with add ons there are hidden charges. The below doc says about the usage of a plugin but it didn't work. https://blog.heroku.com/tech_sending_email_with_gmail Are any other ways possible? -
Django mptt, can I delete the default 'name' filed?
I'm following the django-mptt tutorial,and there is a 'name' filed: class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] compare to my own model: class Comment(MPTTModel): """ 评论表 """ name = models.CharField(max_length=1500, unique=True,) nid = models.AutoField(primary_key=True) news = models.ForeignKey(verbose_name='评论文章', to='News',to_field='id',on_delete=models.CASCADE) user = models.ForeignKey(verbose_name='评论者', to='User',to_field='id',on_delete=models.CASCADE) content = models.CharField(verbose_name='评论内容', max_length=255) create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] This 'name' filed is really bothers me, since each time I need to add this filed. My question is can I hidden or ignore this filed? -
Django GenericRelation Game Engine
I am working on a boardgaming site. I have the following classes: GameType (Tic-Tac-Toe, Chess...) Game (Chess game between Player1 and Player2 played on this date and so on) GameEngine (encodes the rules for playing) Now, I want every GameType to have a ForeignKey to a GameEngine. But GameEngine should be an abstract model, with children like TicTacToeEngine, each one implementing its own is_valid_move method. Since every game's engine will be a different model, it seems that I need GenericRelation, but I don't understand them well. Here are the questions: Is a GenericRelation my only choice? Can I have a ForeignKey to children of a certain abstract model class? If I do need a GenericRelation, how does the syntax work? I have the following code but I am not sure this is the right approach. I am getting errors when trying to access the is_valid_move method. class GameType(models.Model): name = ... num_players = ... slug = ... rules = ... engine_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) engine_id = models.PositiveIntegerField() engine = GenericForeignKey('engine_type', 'engine_id') def is_valid_move(self, *args, **kwargs): return self.engine.is_valid_move(*args, **kwargs) class GameEngine(models.Model): name = models.CharField('Name of the game', max_length=50) def __str__(self): return f"Engine {self.name}" class Meta: abstract = True class TicTacToeEngine(GameEngine): game … -
Django - best practice for making queries inside a Model?
I'm interested in clarifying if there are django Best Practices for making queries from inside Models, specifically regarding Record-Level vs. Table-Level querying. To clarify, I'm aware of the distinction between "table-level" queries made on a Model's Manager, and "record-level" queries, made on an instance of a Model and (at least per the Django docs) usually or often performed via Model methods. However, when writing Model methods that perform queries, it appears interchangeable to me whether the query is performed on the record-level or the table-level. I can retrieve the desired related objects I need either through the model's FK field connecting to the related model (record-level), or through the Model manager of the object I want to retrieve (table-level). So my question is, does it matter which I use? Here is a simplified project of mine, to illustrate the question. I have a UserProfile that stores data related to a given User. All Users participate in Rounds of a game, and the points they earn for a Round are stored in an intermediary table called UserRoundScore (there is a M2M between User and Round, and UserRoundScore is the defined intermediary table). The goal here is to add a method to … -
How to acess a object pk
So, im using the shell intarctive console and doing this in my_app.models im created this Model class Mercadoria(models.Model): name = models.CharField(max_length=50, primary_key=True) price = models.FloatField() def __str__(self): return self.name ------------------------------------------------------------------ from my_app.models import Mercadoria, Sell mercadoria = Mercadoria.objects.all() mercadoria <QuerySet [<Mercadoria: Babydool>, <Mercadoria: Brinco>]> how can i acess a specifig object taking as parameter my pk i`m improving my english, so be patient :D -
Django using variables in Template Tag
the website that I'm working on is using a model for a post, and another linked model for an image that would be attached to the post. page_choices = { ('news', 'news'), ('activities', 'activities'), ('environment', 'environment'), ('affairs', 'affairs'), ('links', 'links'), } link_choices = { ('external', 'external'), ('none', 'none'), ('pdf', 'pdf'), ('image', 'image'), } class Post(models.Model): id = models.AutoField(primary_key=True) page = models.CharField( choices=page_choices, max_length=11, default='news', ) title = models.CharField(null=True, max_length = 100) content = models.CharField(null=True, max_length = 10000) image_filename = models.ForeignKey('Image', on_delete=models.DO_NOTHING, null=True, blank=True) has_image = models.BooleanField(default=False) class Image(models.Model): id = models.AutoField(primary_key=True) image_file = models.ImageField() name = models.CharField(null=True, max_length = 100) identifier = models.CharField(null=True, max_length = 100) alt_text = models.CharField(null=True, max_length = 100) link_address = models.CharField(null=True, blank=True, max_length = 100, help_text="Optional") link = models.CharField( choices=link_choices, max_length=8, default='none', ) These models are presented by the view to the HTML, and I'm trying to add JS/jQuery to add link functionality to the image. I'm trying to get a link to the static directory for an pdf that should be rendered when an image is clicked. {% if post.image_filename.link == "pdf" %} <script> $(document).ready(function() { $("#{{post.image_filename.identifier}}").click(function() { location.href = "{% static 'images/{{ post.image_filename.link_address }}' %}"; }); }); </script> {% endif %} Putting {{ }} … -
Wagtail Form Builder Page customization
How do we get Wagtail's Form builder to allow multiple fields in a single line? For example, I would like to have a First Name field, a Middle Name field, and a Last Name field all on the same line. Using the given code in the documentation, the HTML template generates each FormField on separate lines. Also a note, I do want to maintain the flexibility of the current Form builder. I want to avoid hard coding in fields in the HTML as much as possible. This also means that it doesn't necessary have to be just single line fields populating a single line on the form. It could also be a single line field and a boolean. For example, there could be a single line text field with "Ice Cream Shop name" and then a boolean field with "Favorite?" to the right of it on the same line. So far, my thought process has been that perhaps we create custom Form Field types but I'm not sure if Wagtail can support multi Field Types in a single Field Type. What would be the right direction for this implementation? For convenience, here's the code from the documentation: models.py from modelcluster.fields … -
Can I convert Domain-driven website of Django to Django Rest API?
Django-Oscar is the domain-driven E-Commerce framework. I wanted to connect the frontend with the mobile app through Rest API. Can I use the Django Rest API framework for this? IF so will it be efficient? -
How to automatically add a profile to a ManyToManyField?
I have this model of a course class Minicursos(models.Model): nome_minicurso = models.CharField(max_length=150) resumo = models.TextField(max_length=500, default = "") descricao = models.TextField(max_length=500, default = "") imagem_minicurso = models.ImageField(upload_to="gallery", height_field=None, width_field=None, max_length=None, default = "") video_explicativo = models.FileField(upload_to="video/%y", default="",) carga_horaria = models.IntegerField() alunos = models.ManyToManyField(Profile, 'Alunos') my html is like this {% if user.is_authenticated %} <form id="ingressar-form" method="POST"> {% csrf_token %} {{ form.as_p }} <a href="/minicurso/{{minicurso.id}}/aulas.html"><button id="ingressar" type="submit" value="Create">INGRESSAR</button></a> </form> {% else %} <strong><p>Para ingressar no minicurso faça <a href="/login">Login</a> ou <a href="/register">Registre-se</a>.</p></strong> {% endif %} I wish that when the user clicks on 'ingressar' his profile, it will be added to the field students (alunos) i tried it if request.method == 'POST': aluno = Minicursos.alunos.add(User) aluno.save() but I get this error aluno = Minicursos.alunos.add(User) AttributeError: 'ManyToManyDescriptor' object has no attribute 'add' Someone can help me please!? -
Adding query definition to Swagger
I have a GET method in my api, which gets location as a query. When I add the following definition to the urls array, I can see the api definition, but I don't know how can add a definition path('openapi', get_schema_view( title="My Api", description="My description", version="1.0.0" ), name='openapi-schema'), I want to add something like this: parameters: - in: query name: location schema: type: string description: Location to search for. How can we add this to openapi structure? -
How should I store files inside Django
I am writing an application in Django Rest Framework that accepts employee data and generates a barcode for him in pdf format. then I have to give these files on request. question: how should i store the files created in the application? I have a model of the employee itself and I have a second model with a one-to-one relationship with the employee model and a field for the file. what type of field to use: FileField or FilePathField? the generated files will be stored on the server. they will have to be given through the API in the form of binary data -
How to filter an exact match of ForeignKey field when using Django Elasticsearch
I'm using Django Elasticsearch DSL with Django 3 app, PostgreSQL and Elasticsearch. As models I have (simplified version) class Jornal(models.Model): name = models.CharField(max_length = 250) slug = models.CharField(max_length = 250,blank=True,null = True,unique = True) class Article(models.Model): title = models.CharField(max_length = 250) description = models.TextField() jornal = models.ForeignKey(Jornal,on_delete=models.CASCADE,related_name = 'jornal') I want to filter a query by the jornal slug. For that, I have this q = Q("multi_match", query=termo, fields=['title','description']) entries = ArticleDocument.search().query(q) entries = entries.filter("match",jornal__slug = jornal_slug) It works except for the jornal slug. It does not filter as an exact match. -
How do I get my django app to successfully talk to my bokeh server when they're in separate docker containers?
I am using bokeh server to render some data as part of a django app, and containerising the project using docker. This gives me 3 apps: bokeh_server_app nginx_app django_app When I use docker-compose to build these apps, they all run without issue. I can access django_app via the correct url, and bokeh_server_app runs as expected. Unfortunately, I am unable to to get django_app to talk to bokeh_server_app via the bokeh.server_document function. I can get django_app to talk to bokeh_server_app when I use requests. bokeh_server_app/Dockerfile FROM continuumio/miniconda3 WORKDIR /bokeh_server_app RUN conda config --append channels conda-forge RUN conda install -y bokeh EXPOSE 5006 COPY . /bokeh_server_app/ RUN chmod +x /bokeh_server_app CMD ["bokeh", "serve", "bokeh_server_app", "--allow-websocket-origin=django_app", "--allow-websocket-origin=localhost:5006"] If I hit this from http://localhost:5006 on the bokeh_server_app container, the graph renders as expected - so I'm confident this is running as it should. Over on the django_app: django_app/testintegrationbokeh.py from django.test import TestCase import requests class TestServerUp(TestCase): def test_hit_endpoint(self): r = requests.get('http://bokeh_server_app:5006') self.assertEquals(r.status_code, 200) This passes and I can see the logs and graph render on bokeh_server_app. django_app/views.py from django.shortcuts import render from bokeh.embed import server_document from models import Foo def getgraph(request, pk): script = server_document(url='http://bokeh_server_app:5006', arguments={"pk":pk,}, ) foo = Foo.objects.get(pk=pk) return render(request, 'getgraph.html', {'script':script, … -
Django Annotate foreign key - user specific status to an object
There are Widget and UserStatus models. Challenge: Get a QuerySet of widgets, annotated with unified status from user and widget. Logic: If has user status, use that, else use the widget's status. https://gist.github.com/Lucianovici/53c00ec62f631580dac774cfa4a1578b class WidgetManager(models.Manager): def with_user_status(self, user: User = None): """This approach duplicates the same widget for each UserStatus""" return self.annotate( unified_status_id=Case( When(user_status__user=user, then='user_status__status_id'), default=F('status_id'), output_field=models.IntegerField(), ) ).order_by('unified_status_id') class Widget(models.Model): STATUS_NOK = 1 STATUS_OK = 2 STATUS_NONE = 3 name = models.CharField(max_length=40) status_id = models.IntegerField(default=STATUS_NONE) objects = WidgetManager() def __str__(self): return f'{self.name} - status: {self.status_id}' class UserStatus(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) widget = models.ForeignKey(to=Widget, on_delete=models.CASCADE, related_name='user_status') status_id = models.IntegerField(default=Widget.STATUS_NONE) def __str__(self): return f'{self.widget.name} - status: {self.status_id}' Let's try it out. u1 = User.objects.filter(username='user1').first() or User.objects.create_user('user1') u2 = User.objects.filter(username='user2').first() or User.objects.create_user('user2') w1 = Widget.objects.create(name='Widget1', status_id=Widget.STATUS_NONE) w2 = Widget.objects.create(name='Widget2', status_id=Widget.STATUS_OK) w3 = Widget.objects.create(name='Widget3', status_id=Widget.STATUS_NOK) UserStatus.objects.create(user=u1, widget=w1, status_id=Widget.STATUS_NOK) UserStatus.objects.create(user=u2, widget=w1, status_id=Widget.STATUS_OK) qs = Widget.objects.all() print(f'All widgets: {qs}') qs = Widget.objects.with_user_status(user=u1) print(f'Widgets with user status {[(w.name, w.unified_status_id) for w in qs]}') I get: All widgets: <QuerySet [<Widget: Widget1 - status: 3>, <Widget: Widget2 - status: 2>, <Widget: Widget3 - status: 1>]> Widgets with user status [('Widget1', 1), ('Widget3', 1), ('Widget2', 2), ('Widget1', 3)] Expected result: Widgets with user status [('Widget1', 1), ('Widget3', 1), … -
When is `_result_cache` populated in Django?
I am trying to step through Django code in PyCharm to figure out when _result_cache is actually populated, but it doesn't seem possible (some critical steps seem to be skipped even if I step into every line of code possible). For example, say, I have a view function that does: def my_view(request): data = MyModel.objects.all() for d in data: # do something with every object in the table When I step into this view function, all() is called on BaseManager as expected, which calls get_queryset() to create a new QuerySet instance (i.e., QuerySet's __init__ is called). Once __init__ is finished, data is now a QuerySet instance and its _result_cache is already populated with the data in the MyModel table. But during __init__, it was set to None. So what happened after __init__ is finished? Is some kind of background thread running that I wasn't tracing? -
Run a django script and return the result to React
I'm trying to send lat and lon from a marker from react to django and run a script that will calculate distances between this point with thge ones on my database, how can I achieve this? I'm new to this and I can't find a good tutorial. Input: Marker: -33.442249608 -70.628815668 This is the output of my script on django: [{'Lat': -36.828233049999994, 'Lon': -73.04807725260355}, {'Lat': -39.0989346, 'Lon': -72.6724288}, {'Lat': -34.727836, 'Lon': -71.6440839}] -
How to solve error 'RelatedManager' object is not subscriptable?
I have the following view class CommentViewSet(ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentsSerializer permission_classes = [CustomPermissionClass] pagination_class = MyLimitOffsetPagination def get_queryset(self): review = get_object_or_404(Post, pk=self.kwargs.get('post_id')) return post.comment_set def perform_create(self, serializer): review = get_object_or_404(Post, pk=self.kwargs.get('post_id')) serializer.save(author=self.request.user, post=post) My Custom pagination: class MyLimitOffsetPagination(LimitOffsetPagination): default_limit = 1 max_limit = 10 Getting the following error: 'RelatedManager' object is not subscriptable. Exception location: paginate_queryset If I delete the pagination_class everything is okay. Can't figure out why the code does not working with pagination. Because of comments depend on posts?