Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unregister a viewset from drf router
I have two separate apps Product and Tag which i used another app Product_tags to connect them together. in this way, if one of them don't exists, another one will work fine. inside Product_tags, I created a new TagProductSerializer which inherits ProductSerializer and I just added a new field named tag in fields list. product_tags/serializers.py: class TagProductSerializer(ProductSerializer): tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all()) class Meta: model = Product fields = [ 'title', 'tags', ] #... and I did the same with Product viewsetproduct_tags/views.py class TagProductViewset(ProductViewset): serializer_class = SocialProductSerializer and in my product_tags/urls.py I imported my Product router and i wanted to register my product viewset again for router. and there is my problem: product/urls.py router = routers.DefaultRouter() router.register('product', ProductViewset) urlpatterns = [ path('', include(router.urls)), ] product_tags/urls.py (PROBLEM) from product.urls import router from .views import TagProductViewset router.unregister('product') # I'm looking for something like this router.register('product',TagProductViewset) NOTE: I want to show the tags when getting product and because of that, I don't want to use different url for getting tag (e.g "api/product/tags/") First Try:I tried to register the 'product' again (router.register('product',SocialProductViewset)) but it doesn't works -
Forbidden error When deploying Django App with Apache
I'm trying to deploy my Django project using Apache + mod-wsgi, but it occurred a 403 error which I'm unable to solve. I've substituted the 000-default.conf file to a custom file named Qxt_project.conf in /etc/apache2/sites-available/ Alias /static /home/scodasso/Qxt_project/static <Directory /home/scodasso/Qxt_project/static> Require all granted </Directory> Alias /media /home/scodasso/Qxt_project/media <Directory /home/scodasso/Qxt_project/media> Require all granted </Directory> <Directory /home/scodasso/Qxt_project/django_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/scodasso/Qxt_project/django_project/wsgi.py WSGIDaemonProcess django_app python-path=/home/scodasso/Qxt_project python-home=/home/scodasso/Qxt_project/venv> I've checked and everything points towards the right folder. When I check apache2 errors.log with "sudo tail -100 /var/log/apache2/error.log" I get: import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/scodasso/Qxt_project/venv' sys.base_exec_prefix = '/home/scodasso/Qxt_project/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/scodasso/Qxt_project/venv' sys.exec_prefix = '/home/scodasso/Qxt_project/venv' sys.path = [ '/home/scodasso/Qxt_project/venv/lib/python39.zip', '/home/scodasso/Qxt_project/venv/lib/python3.9', '/home/scodasso/Qxt_project/venv/lib/python3.9/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fb0b30a9d40 (most recent call first): <no Python frame> [Fri Aug 20 22:05:49.134562 2021] [wsgi:warn] [pid 1495344:tid 140396894788928] (13)Permission denied: mod_wsgi (pid=1495344): Unable to stat Python home /home/scodasso/Qxt_project/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for the whole of the path. Python path … -
Querying a Parent object based on a Child M2M's own M2M relationship
I have two types of objects, one is a parent and one is a child: class Parent(models.Model): children = models.ManyToMany(Child) class Child(models.Model): compatable_children = models.ManyToMany("self") I use the Parent object to display in my application, but I need to filter it based on the existence of a child within the compatable_children field. So something like: filter_child = Child.objects.filter(id=blah) queryset = Parent.objects.filter(children__compatable_children__contains=filter_child) How can I achieve something like this query? -
Django application on AWS ECS Fargate keeps restarting after several hours of running successful
I am hosting a Django app on AWS ECS Fargate and I noticed it keeps on restarting after a random number of hours. It runs between 4- 48 hours before restarting. When I check the Event logs of the ECS Task I can see that it is due to health check failure. I have tried everything I know to stop it from restarting, it seems health check failure happens at random after the application has already passed health checks.what can I do to resolve this. Note: The Django app is not running with Nginx reverse proxy, it uses gunicorn wsgi and whitenoise to serve static files. The gunicorn uses one worker with the gthread worker type I also have a similar set on flask but the flask seems to have no issues so I am thinking it’s a Django related issue The Django app also logs a lot of 404 Not Found errors to the cloud watch logs. Any help on this would be appreciated. -
AttributeError: 'ManyToManyDescriptor' object has no attribute 'remove'
I'm trying to make a liking system with LikeView and BlogDetails such as if I like it and then click again I disliked it def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): Post.likes.remove(id=request.user.id) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse_lazy('blog-detail', args=[str(pk)])) class BlogDetails(DetailView): model = Post template_name = 'blog_details.html' def get_context_data(self, *args, **kwargs): categories = Category.objects.all() context = super(BlogDetails, self).get_context_data(*args, **kwargs) context['categories'] = categories liked = False stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() context['likes'] = total_likes if stuff.likes.filter(id=self.request.user.id).exists(): Liked = True context['liked'] = liked return context and it shows an AttributeError: 'ManyToManyDescriptor' object has no attribute 'remove' -
Dockerized Django APP with PostgreSQL does not work
As in title i have an issue, my dockerized app does not work. There is problem with the port. PostgreSQL works fine during development and creating models. I have no idea it changes something but I develop this app in python virtual env. DB settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fitshop', 'USER': 'fitshopuser', 'PASSWORD': 'fitpass', 'HOST': 'localhost', 'PORT': '5432', } } Dockerfile: FROM python:3 RUN adduser --system --no-create-home django ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /django/app RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r ./requirements.txt COPY . . EXPOSE 8000 USER django CMD ["python", "manage.py", "runserver"] ERROR: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? -
How Can I Sum Django Models Field by Dates and Display Totals base on Current Month and Year
I am a novice in python Django framework and I wish someone should please help on some piece of code I have been struggling with hours. I have an Expenditure Model with date and amount Fields among others, and I want to calculate total amount for the current month and display in django template through the views using the context dictionary. Here is my Expenditure model code: class Expenditure(models.Model): amount = models.PositiveIntegerField(null=False) date = models.DateField(auto_now_add=False, auto_now=False, null=False) Views.py codes here: from django.db.models import Count, Sum from django.db import connection def index(request): truncate_month = connection.ops.date_trunc_sql('month','day') total_income = Income.objects.extra({'month': truncate_month}).values('date').annotate(Sum('amount')) context = { 'total_income':total_income, } return render(request, 'dashboard/index.html', context) This is how I am trying to display the Sum Total of amount for the current month and year in Django template. {% for income in total_income %} {{income.date}}{{income.amount}} {% endfor %} The result of my code above is displaying the months of dates from the Expenditure Model on the template. Your kind assistance would help a lot. Thanks -
Select multiple rows from database in views.py and send it as array to html page - Django
I want to select multiple rows in database in Django view and send it as an array to my html page. views.py def report_template(request, pk): template_list = AddScore.objects.filter(template_name=pk) context = {'Template': template_list} return render(request, 'myapp/report_template.html', context) models.py class AddScore(models.Model): score = models.CharField(max_length=100, primary_key=True, default='', blank=True) client_name = models.CharField(max_length=300, blank=True) template_name = models.CharField(max_length=100, blank=True) I want the result like - data = [ ['client_name1', '37.54'], ['client_name2', '33.54'] ]; -
How do I enable the 'trimmed' policy in Jinja2?
I am trying to enable the trimmed keyword for all {% trans %} blocks in Jinja2. I have added env.policies['ext.i18n.trimmed'] = True (found here: https://jinja.palletsprojects.com/en/3.0.x/api/#policies) in my environment configuration, but nothing happens. In my project I am using Babel with Jinja2 and Django to extract messages. Here is my environment configuration: def environment(**options): env = Environment( **options, extensions=[ 'compressor.contrib.jinja2ext.CompressorExtension', 'jinja2.ext.autoescape', 'sass_processor.jinja2.ext.SassSrc', 'jinja2.ext.i18n', ] } env.policies['ext.i18n.trimmed'] = True env.install_gettext_callables(gettext=gettext, ngettext=ngettext) env.globals.update(globals) env.filters.update(filters) return env -
How do I fix a 504 gateway timeout error?
My web application (Django + Nginx) calls another url in the backend. As it takes time like 15-20 minutes to get whatever from the other site, I am running into the 504 Bad Gateway error. Before I encrypted my website, I added the following commands to /etc/nginx/nginx.conf and it worked. proxy_connect_timeout 1800; proxy_send_timeout 1800; proxy_read_timeout 1800; But now my website is transferred from http to https. It does not work any longer. I googled but did not find a solution. Can anybody kindly help with this? Thanks. -
Registration form not saving new users in django
I am following a tutorial and I made my user registration view but it's not saving the user either giving any error. Below is my view file from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('waqart-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) -
xhtml2pdf using border-radius css
I'm looking to create a PDF through xhtml2pdf python package on a Django environment but it seems not possible to add a border-radius to a div :( Do you know other packages in python to do this job ? -
/admin/password_change/ and /accounts/password_change/ use the same template unless I manually specify some urlpatterns
Problem I am using both django auth and django admin. After registering these in urls.py, visiting /accounts/password_change/ and /admin/password_change/ are using the same template. This is not what I want. Environment The following is my project layout, or at least the relevant parts: . +-- config | +-- settings.py | +-- urls.py +-- timelog | +-- templates | | +-- registration | | | +-- password_change_done.html | | | +-- password_change.html | | +-- app1 | | | +-- (templates) | | +-- app1 | | | +-- (templates) | +-- app1 | +-- app2 +-- manage.py TEMPLATES setting: from pathlib import Path ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent APPS_DIR = ROOT_DIR / "timelog" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [str(APPS_DIR / "templates")], "APP_DIRS": True, } ] urls.py: from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path("accounts/", include("django.contrib.auth.urls")), path("admin/", admin.site.urls), ] Current workaround The only solution I found was to override /accounts/password_change/ and /accounts/password_change/done/. I found it necessary to rename the templates so that include("django.contrib.auth.urls") wouldn't screw things up. Updated urls.py from django.conf.urls import include from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path( "accounts/password_change/", auth_views.PasswordChangeView.as_view(template_name="registration/change_password.html"), … -
How to know the count of many to many fields of an random model?
I have an random model: class Model(models.Model): other_field1 = models.SomeField(...) m2m_field1 = models.ManyToManyField(...) other_field2 = models.SomeField(...) m2m_field2 = models.ManyToManyField(...) other_field3 = models.SomeField(...) I want to know the count of fields that correspond to the relation many to many and the count of other fields. In the example above, I have 2 fields with a many-to-many relationship and 3 other fields. -
How to allow the update of only 1 field?
So Im doing an app where the user can upload photos, each photo has a user, image, description, and other fields. When the user creates a new photo, the image is required, but when the user wants to update it, you only can change the description. I'm stuck with this, first tried with update (put) but it's clearly not the method to use, now I'm trying with partial_update but I can't get it right. This is what I have right now, it gives me the error: TypeError: Object of type Photo is not JSON serializable. Maybe it's a completely wrong way of doing it. View: class PhotoViewSet(mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): """ PhotoViewSet Handle upload (create) and delete of photos. """ queryset = Photo.objects.all() serializer_class = PhotoModelSerializer def perfom_create(self, serializer): """ Upload a new photo. """ serializer.save() def perform_destroy(self, instance): """ Delete a photo. """ return super().perform_destroy(instance) def retrieve(self, request, *args, **kwargs): """ Retrieve photo information. """ response = super(PhotoViewSet, self).retrieve(request, *args, **kwargs) data = { 'photo': response.data, } response.data = data return response def partial_update(self, request, pk=None): serializer = UpdateDescriptionSerializer(data=request.data, partial=True) serializer.is_valid(raise_exception=True) data = serializer.save() return Response(data=data, status=status.HTTP_202_ACCEPTED) serializer: class UpdateDescriptionSerializer(serializers.ModelSerializer): """ Update description serializer. """ description = serializers.CharField(max_length=255) … -
Get queryset and it's aggregated value at one db query
In Django rest framework view I am making a complex Product annotated queryset which goes to serialization, but at the same time, I need to get its aggregation data to add it to the Response data. Example (one query): qs = self.filter_queryset(Product.objects.filter(**query_filters) .annotate(current_price=F('some_value') * some_vart))) Then I need aggregated data(second query): min_max = qs.aggregate(Max('current_price'), Min('current_price')) This produces 2 DB queries total. Is there any way to make it hitting DB once? DB is Postgres. Thx -
Django migrations weren't unapplied
I've developed a custom package to sync some models with s3 bucket. When I installed it on my django app, and ran the CI, the migrations weren't unapplied. The unapplying migrations are behaving unexpectedly: It tries to unapply twice the same migration (recommendations.0011_auto_20210725_1253): Operations to perform: Unapply all migrations: lakehouse_sync Running migrations: Rendering model states... DONE Unapplying lakehouse_sync.0001_initial... OK INFO:botocore.credentials:Found credentials in shared credentials file: ~/.aws/credentials Operations to perform: Unapply all migrations: profiles Running migrations: Rendering model states... DONE [...] Unapplying recommendations.0011_auto_20210725_1253... OK [...] Operations to perform: Unapply all migrations: recommendations Running migrations: Rendering model states... DONE Unapplying recommendations.0011_auto_20210725_1253 And it happens because Django doesn't detect that they were unapplied. lakehouse_sync [X] 0001_initial profiles [X] 0001_initial [X] 0002_auto_20210723_0857 recommendations [...] [X] 0011_auto_20210725_1253 However, there aren't those tables on my db I have no idea how to proceed with that, could someone give me a clue at least to solve this issue? -
Which stack, technologies and tools for building online store?
I want to build an online store for subscription boxes with recurrent payments. I study computer science and have experience in most of the popular programming languages (have been using python for the last semesters). Which stack, technologies and tools do you recommend me to use? And any other tips for building an online store. -
Django run javascript before render_to_string
I am building a application that dynamically fill in forms and converts it to pdf. To build the pdf I pass in html code (pdfkit.from_string()) and to build the html code I am using Django templates. I need to run some Javascript code to mark some input checkboxes as checked, however render_to_string will just generate the html without running the javascript to mark the items as checked. my_template.html {{checked_items|json_script:'items'}} <script src="{% static 'form_render.js' %}"></script> form_render.js const items = JSON.parse(document.getElementById("items").textContent); let form_checkboxes = document.querySelectorAll('input[name="my_checkboxes"]'); for (let i of form_checkboxes) { items.includes(i.value) ? (i.checked = true) : ""; } views.py rendered = render_to_string( "my_app/my_template.html", {"checked_items": checked_items_json}, ) -
Make Swagger UI to use HTML Form to submit request body, just like DRF's browsable API
In django-rest-framework's browsable API, there is an HTML form to submit in the request body. Swagger on the other hand lets you edit a JSON formatted text as the request body. How to make Swagger UI show HTML form, just like DRF's browsable API in swagger? -
Pyhton django, when creating an registering form how to get this .get method working?
I started to watch Corey Schafer's django website tutorial and everything was going great until now. unlike in the video after registering site doesn't sends me to home page. It does nothing. All I suspect is the get method because it is not the color it supposed to be in VSC. Any ideas why :( and also .method functions seems to be not working it is white in VSC from django.contrib import messages from django.contrib.auth.forms import UserCreationForm from django.shortcuts import redirect, render def register(request): if request.method =='POST': form = UserCreationForm(request.POST) if form.is_valid(): username=form.cleaned_data.get('username') messages.success(request,f'Account Created for {username}') return redirect("blog-home") else: form=UserCreationForm() return render(request,'users/register.html',{'form':form}) -
Django: How to delete models in real time
I am working on a subscriber confirmation system with Django, and I do not want random/spam subscribers. So I came up with a confirmation system. Once the subscriber clicks the subscribe button, a Subscriber model is created. However, it is not confirmed. I send a confirmation email and only if the subscriber clicks on the link in the email will the model be confirmed. The problem with this system is that an unconfirmed subscriber stays and is not deleted. How do I write a function that deletes the unconfirmed subscribers if they did not confirm in, say, 2 days? models.py class Subscriber(models.Model): email = models.EmailField(unique=True) confirmed = models.BooleanField(default=False) creation_date = models.DateTimeField('date published', blank=True, null=True) #my function for deleting subscribers def confirm_date(self): today = date.today().toordinal() if today - self.ordinal_creation >= 2 and self.confirmed == False: self.delete() -
how do I create an online compiler? like TIO?
So, I'm working on a hobby project, and so basically what I want is something like 'TIO' (try it online) Where the user would enter the 'code' hit 'Run', and the server would return the appropriate output firstly I was thinking of using a third party library Python-tio-github and simply sending a request to the 'Tio' website, but that doesn't seem right, I mean is that allowed?, is there any other way? how am I supposed to go about it? My Setup: I'm using Django, 'Rest Api' with Angular 10, and I'm planning on running this on Digital Ocean I could run the TIO on my website server (as it's open-source) but I doubt the server would be able to handle it? running Django, node(angular), and MySQL along with TIO? the main goal of this project is for me to learn, so, even if I could have only a single language compile (Python) I'd be happy, I just don't have ANY clue on how and where I'd start looking. thanks in advance! -
paypal sandbox not working after adding the client id
hello everyone im sorry if this is a silly question ,it's my first time trying to integrate paypal payment button to my django website i was following a tutorial and everything works fine when i used the html script from paypal developer website : https://developer.paypal.com/demo/checkout/#/pattern/client i tested the payments and it went through successfully. this is the working script <!-- Set up a container element for the button --> <div id="paypal-button-container"></div> <!-- Include the PayPal JavaScript SDK --> <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script> <script> // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '88.44' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(orderData) { // Successful capture! For demo purposes: console.log('Capture result', orderData, JSON.stringify(orderData, null, 2)); var transaction = orderData.purchase_units[0].payments.captures[0]; alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details'); // Replace the above to show a success message within this page, e.g. // const element = document.getElementById('paypal-button-container'); // element.innerHTML = ''; // element.innerHTML = '<h3>Thank you for your payment!</h3>'; // Or go to another URL: actions.redirect('thank_you.html'); }); } }).render('#paypal-button-container'); </script> on the final step i should add … -
couldn't makemigrations in django
i had this erreur . Traceback (most recent call last): File "C:\Users\abdou\Documents\Djangoprojects\DjangoAPI\manage.py", line 22, in main() File "C:\Users\abdou\Documents\Djangoprojects\DjangoAPI\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\makemigrations.py", line 103, in handle loader.check_consistent_history(connection) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 294, in check_consistent_history applied = recorder.applied_migrations() File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table tables = self.connection.introspection.table_names(cursor) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\introspection.py", line 52, in table_names return get_names(cursor) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\introspection.py", line 47, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\database.py", line 880, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\database.py", line 842, in list_collections return self.__client._retryable_read( File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\mongo_client.py", line 1514, in _retryable_read server = self._select_server( File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\mongo_client.py", line 1346, in _select_server server = topology.select_server(server_selector) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\topology.py", line 244, in select_server return random.choice(self.select_servers(selector, File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\topology.py", line 202, in select_servers server_descriptions = self._select_servers_loop( File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\topology.py", line 218, in _select_servers_loop raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: djangoapi-shard-00-02.wqh9l.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get …