Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there something I am doing wrong with my Content Aggregator Website?
I followed an online tutorial, but was able to scrape different websites. I cannot get the article headlines to show up. I am not sure if it is a problem with my return function or my HTML file. This is how the website comes out -
Displaying fields based on user's preference
I would like to know if there's a cleaner, easier, more practical way of implementing below scenario. Currently I let users choose to either have required(red), optional(red) or hidden(black) fields(pre-defined) in the webapp. I store user's preferences in db such as [input_field : user_choice]. Since bootstrap allows 12 columns in a single row, , I was thinking if by adding additional fields [order, size] I could allocate required and optional fields in a proper order. Size can range from 1-12 and order can have duplicate values. {'field_name': 'somename1', 'user_choice': 'Required', 'order': 1, 'size': 6}, {'field_name': 'somename2', 'user_choice': 'Optional', 'order': 2, 'size': 6}, {'field_name': 'somename3', 'user_choice': 'Required', 'order': 3, 'size': 12}, {'field_name': 'somename4', 'user_choice': 'Required', 'order': 4, 'size': 6}, {'field_name': 'somename5', 'user_choice': 'Hidden', 'order': 4, 'size': 6}, {'field_name': 'somename6', 'user_choice': 'Hidden', 'order': 5, 'size': 6}, {'field_name': 'somename7', 'user_choice': 'Required', 'order': 6, 'size': 6}, {'field_name': 'somename8', 'user_choice': 'Hidden', 'order': 7, 'size': 6}, {'field_name': 'somename9', 'user_choice': 'Hidden', 'order': 8, 'size': 3}, {'field_name': 'somename10', 'user_choice': 'Hidden', 'order': 9, 'size': 3}, {'field_name': 'somename11', 'user_choice': 'Optional', 'order': 10, 'size': 12} Based on that I would filter to get only objects that have value of Required and Optional and loop in such way that would allow to … -
Get ManytoMany Objects in Django
I am trying to solve an issue. Like I have two model service and package. package has relation with service in many to many. I want to get the service's name which are not having any many to many relation with the package table. How to do this? I have tried multiple apporch. #models.py class Service(models.Model): name = models.CharField(max_length=1000) price = models.IntegerField(null=True, blank=True, default=0) details = models.TextField(max_length=20000, blank=True, null=True) status = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Package(models.Model): service = models.ManyToManyField(Service, blank=True) name = models.CharField(max_length=220) price = models.IntegerField(null=True, blank=True, default=0) details = models.TextField(max_length=20000, blank=True, null=True) status = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) #views.py children_id_list = [2, 1, 4] temp = [] for i in children_id_list: try: s = Service.objects.get(id=i) t = s.package_set.all() if len(t) == 0: children_id_list.remove(i) temp.append(i) except ObjectDoesNotExist: print(f'Sorry! There is no Service List with this ID {i}') print(children_id_list) print(temp) print(f"\n") package = Package.objects.filter(service__in=children_id_list).annotate(num_cats=Count('service')).filter(num_cats=len(children_id_list)).exclude(service__in=Service.objects.exclude(id__in=children_id_list)) for i in package: print(f"Hello, Package Name {i.name} and Price {i.price} BDT") if len(temp) > 0: c = Service.objects.get(id=temp[0]) print(f"Addon for new service {c.price} BDT") u = i.price + c.price print(f"Total Checkout {u} BDT") print(f"\n") else: print('None') -
Django rest framework clears FileField on PUT form submission of other fields
I have an optional FileField in my model which can be e.g. set in the POST method. Unfortunately this field gets always cleared in the PUT method. My model is defined like this: class MyModel(models.Model): myfile = models.FileField(upload_to=_upload_to, blank=True, null=True) This works as expected in the Django Admin page giving me the option to set a "Clear" checkbox explicitly. But in the Django Rest Framework form I can create a new instance with POST but if I then update my model with PUT it not only updates the changed fields but also clears my FileField. My serializer class looks like this: class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ['url', 'id', 'myfile'] I also tried with this in the serializer to no avail: myfile = serializers.FileField(required=False, allow_null=True) -
output_field argument of expressionwrapper not identifying any field
while using ExpressionWrapper i am not able set output_field=DecimalField() i am getting error like Exception Type: NameError Exception Value: name 'DecimalField' is not defined from django.shortcuts import render from django.db.models import Value, F, ExpressionWrapper from store.models import Customer, Product def say_hello(request): discounted_price = ExpressionWrapper( F('unit_price') * 0.8, output_field=DecimalField()) queryset = Product.objects.annotate(discounted_price=discounted_price) return render(request, 'hello.html', {'name': 'Ashish', 'result': list(queryset)}) -
Product form through class based CreateView
I am trying to create a product form by 'Create View' as a class-based view, but it tells there is an issue in the terminal as the following snippet. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Products(models.Model): def __str__(self): return self.product_name user_name=models.ForeignKey(User, on_delete=models.CASCADE, default=1) product_name=models.CharField(max_length=200) product_descript=models.CharField(max_length=200) product_price=models.IntegerField() product_image=models.CharField(max_length=500, default='#') def get_absolute_url(self): return reverse('food:detail', kwargs={'pk':self.pk}) url.py from django.urls import path from . import views urlpatterns=[ path('addj',views.CreateProduct.as_view(),name='add_product'), ] views.py from django.views.generic.edit import CreateView from .models import Products class CreateProduct(CreateView): model= Products fields=['product_name','product_descript','product_price','product_image'] template_name='food/product-form.html' def form_valid(self,form): format.instance.user_name=self.request.user return super().form_valid(form) product-form.html <form method="POST" > {% csrf_token %} {{form}} <button type="submit"> </form> Can someone help me with this regard? Thanks -
How do I convert json data to django models
This is my json data. I want make a django model from this json data { "total_size": 6, "type_id": 2, "offset": 0, "products": [ { "id": 1, "name": "Panta Ilish", "description": "this is description", "price": 150, "stars": 5, "img": "images/pantailish.jpg", "location": "Dhaka, Bangladesh", "created_at": "2022-03-23 06:35:34", "updated_at": "2022-03-23 06:35:34", "type_id": 2 }, { "id": 2, "name": "Kacchi Biryani", "description": "this is description", "price": 200, "stars": 5, "img": "images/kacchi.jpg", "location": "Dhaka, Bangladesh", "created_at": "2022-03-23 06:35:34", "updated_at": "2022-03-23 06:35:34", "type_id": 2 } ] } -
Django Logging in AWS Cloudwatch - Impossible to configure handler
I am able to log, upload and view logs into AWS Cloudwatch; I have no warning locally, but In github action when doing a PR, I keep receiving the error: ValueError: Unable to configure handler 'watchtower-error ``` Below you can see the logging configuration in settings.py CLOUDWATCH_AWS_ID = env("CLOUDWATCH_AWS_ID") CLOUDWATCH_AWS_KEY = env("CLOUDWATCH_AWS_KEY") logger_boto3_session = Session( aws_access_key_id='AKIAUGB2EEYCAPYI2CXS', aws_secret_access_key='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', region_name='eu-west-2', ) LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "aws": { "format": "%(asctime)s [%(levelname)-8s] %(message)s [%(pathname)s:%(lineno)d]", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "handlers": { "watchtower-info": { "level": "INFO", "class": "watchtower.CloudWatchLogHandler", "log_group": "CWOSLogs", "stream_name": f"logs", "formatter": "aws", }, "watchtower-error": { "level": "ERROR", "class": "watchtower.CloudWatchLogHandler", "log_group": "CWOSLogs", "stream_name": f"logs", "formatter": "aws", }, "console": {"class": "logging.StreamHandler", "formatter": "aws",}, }, "loggers": { "wella": {"level": "INFO", "handlers": ["watchtower-info"], "propogate": False}, "wellacaaa": {"level": "ERROR", "handlers": ["watchtower-error"], "propogate": False}, }, } Any suggestion? -
How to configure multiple django project running on different system ports using same IP with gunicorn
This question is a bit lengthy, but I tried to provide as much information as possible from my doubts and trials. I've been fiddling with gunicorn and nginx configurations to host 3 django projects on an AWS EC2 ubuntu server. I've been unable to sort them to run, neither been able to fully understand the settings. (1) First of all I have them them as follows (Each project folder has its own venv setup): drwxrwxr-x 10 ubuntu ubuntu 4096 Mar 26 02:10 first_project/ drwxrwxr-x 7 ubuntu ubuntu 4096 Mar 26 01:20 second_project/ drwxrwxr-x 7 ubuntu ubuntu 4096 Mar 26 01:25 third_project/ (2) I tried creating separate .socket files in /etc/systemd/system/ folder -rw-r--r-- 1 root root 112 Mar 26 02:17 gunicorn_first.socket -rw-r--r-- 1 root root 112 Mar 26 02:19 gunicorn_second.socket -rw-r--r-- 1 root root 112 Mar 26 02:22 gunicorn_third.socket (3) and included all of them with same content: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target (4) Post adding .socket files, I added .service files -rw-r--r-- 1 root root 112 Mar 26 02:35 gunicorn_first.service -rw-r--r-- 1 root root 112 Mar 26 02:39 gunicorn_second.service -rw-r--r-- 1 root root 112 Mar 26 02:44 gunicorn_third.service (5) and added content as follows (NTH -> first , … -
Implementing User specific password expiry in Django ( eg resetting every 90 days for subset of customers)
The Django app I'm building will need to accept different security policies from different User Groups. One such policy is having a customizable password-expiry rule for different users. I've looked at django-allauth and other common authentication packages and they all have great solutions if you're looking to treat all users the same. The one package I've found that implements some sort of user-based system is django-user-accounts. Here's the description: https://django-user-accounts.readthedocs.io/en/latest/commands.html However, I'd like a cleaner implementation than having to run a command for each user, any suggestions? -
Django and Oracle Database
I'd like to connect an Oracle 8i database to Django. I tried using cx-Oracle, but the terminal output is 'cx-Oracle does not support this database'. If anyone know this please help. I tried to connect with cx-Oracle. -
Django Cache - using in a class based view with an S3 presigned url
I have added database caching to my class based view like so: @method_decorator(cache_page(30), name='dispatch') class MyListView(ListView): model = MyModel MyModel is a pretty simple model with some varchar fields, along with a foreign key relationship to an image model. class MyModel(index.Indexed, models.Model): sku = models.CharField(max_length=10, unique=True) ... more fields class MyImageModel(models.Model): def get_sku(instance, filename): return f"{instance.parent.sku}/{filename}" parent = models.ForeignKey(MyModel, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=get_sku) I am using django-s3-storage for my storage backend. This will make a call to get_presigned_url (which uses boto3) when I ask for the image's url in a template: {% for model in object_list %} <p>{{model.sku}}</p> <img src="{{model.images.0.image.url}}"> {% endfor %} I see the view's cache entry show up in my database cache table, but the presigned url that is generated is still unique after reloading the page. Why is this presigned url not cached along with the rest of the generated class based view? -
Email verification not working with deployed django app on heroku
I've deployed a django website with Heroku. When a user creates an account in the app, a validation email is supposed to be sent. Do do that, I'm using smtp from gmail, and in my account settings, I've activated "less secure app access". This works perfectly fine on my local machine, but when using the deployed app, I can't get the email to be sent. The first time, I got a security warning from google saying someone connected to my account. I said it was me and tried again. I didn't get any other security warning but it seems the app is still unable to send emails. Please, let me know if you have any idea what the issue might be. Thanks. -
Why isnt my django heroku admin not working
I created a heroku superuser using the "heroku run python manage.py createsuperuser" command but when i try to log in to my admin pannel in heroku it tells me i am putting wrong login credentials even though they are correct. -
CSS isn't in my website but I wrote in the folder
I created a website (on local host for now), so I linked html with css and my css is ready. I wrote everything, but then the css doesnt show on the website I opened the inspect element > sources > style.css and I found the css empty, but in vs code it has 1200 lines in google its 0 (I saved the folder after writing the css) heres the html code that I used to link html with css <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <link href="{% static 'css/style.css' %}" rel="stylesheet"> -
java script to enable and disable a button based on changes in form
i am using a javscript to enable a button based on the changes in the form field in django python using bootstrap.below is the script $("#employee_name, #employee_name2").on("keyup",function() { $(".btn-action").prop("disabled",false); if( ($("#employee_name").val()) == ($("#employee_name2").val())) { $(".btn-action").prop("disabled",true); } }); also the below code in html to initially disable button <button type="submit" class="btn btn-primary mt-3 btn-action" disabled>Save</button> but the button stays disabled even after changing values in the field.any help would be appreciated -
Even though password is incorrect the user is validated and passes the authentication check in django
I am using landsatxplore API to download satellite images and now I am creating a web application to do that using the same API in Django. In simple python script. from landsatxplore.api import API username = 'username' password = 'password' api = API(username, password) if the username and password are correct it creates an API instance/Key and if the username and password is incorrect it throws an exception: landsatxplore.errors.USGSAuthenticationError: AUTH_INVALID: User credential verification failed. I am trying the same logic in Django but even if I type the wrong username and password it passes the authentication and sends me to the next page homepage.html which should only be accessible if the username and password is correct. views.py from landsatxplore import errors from django.shortcuts import render,redirect from django.contrib import messages from landsatxplore.api import API # Create your views here. def index(request): username = request.POST.get('username') password = request.POST.get('password') if username == None or password == None: messages.info(request,"please Enter the username and password") else: try: # Initialize a new API instance and get an access key api = API(username, password) except errors.USGSUnauthorizedError: messages.info(request,"Username and password is wrong") else: return render(request,"homepage.html") return render(request, 'index.html') def homepage(request): return render(request,'homepage.html') HTML: {% for message in messages … -
Install Django on windows
Pretty Printed 81 k suscribers In this video I will show you how to install Django on Windows and get started with a simple "Hello World" example. -
How to Compare ManyToManyField to another ManyToManyField
I have a model of Partner class Partner(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group = models.OneToOneField( Group, on_delete=models.DO_NOTHING, blank=True, null=True) def __str__(self): return self.name I have 2 other models one is CustomUser and other is Quote class CustomUser(AbstractUser): #... name = models.CharField(max_length=160, null=True, blank=True) partner = models.ManyToManyField( Partner, blank=True) class Quote(models.Model): #... visibility = models.CharField(max_length=10) partner = models.ManyToManyField( Partner, blank=True) Both have a partner field related with ManyToManyField to Partner Model Now I want to compare them in the views like: partner field can have multiple partners like partner1, partner2, partner3 how to to find the partners matching to each other inside the Quote and CustomUser model Lets say, One of the Quote object have set of [partner1 and partner6] in the ManyToManyField and I only want to have access to that quote to users who also have partner1 and partner6 in their partner ManyToManyField set. So how can I filter and compare them ? I also read the docs but didn't able to reproduce the solution. help would be appreciated. -
I want to get users by their role and loop through them and send mail to them django
Pls I want to get all users by their specific role, loop through them, and send mail to them using office 365 send_mail( 'Subject here', 'Here is the message.', 'stack@gmail.com', ['mail@gmail.com'], fail_silently=False, ) -
Django Admin Search Results Doesn't List All Results
The Django Admin change list isn't displaying all of the search results. It says that there's 14 results but it only lists 5 of them. Sometimes it says how many results there are, but it doesn't even show any of them at all. Any ideas what could be going on here? -
Django - [Errno 13] Permission denied: '/audio'
I am facing this error with my django server in production mode. While developping, everything was working fine. Here is the Model concerned : class Music(models.Model): name = models.CharField(max_length=100) cover = models.TextField() prix_son = models.FloatField(default=0) stripe_audio_price_id = models.CharField(max_length=100, default='none') lien_deezer = models.CharField(max_length=500) lien_spotify = models.CharField(max_length=500) audio_file = models.FileField(blank=True, upload_to='audio') def __str__(self): return(self.name) Here is the traceback : Environment: Request Method: POST Request URL: https://www.algorabsdream.fr/admin/test_django/sortie/1/change/ Django Version: 4.0.3 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth' , 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'test_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/test_django/algorab_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/test_django/algorab_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1888, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/test_django/algorab_env/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1745, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/options.py", line … -
how to count the number of users with a certain group in django?
num_moder = django.contrib.auth.models.Group.objects.count() this command count only the number of group dont count members of this group :D the name of the Group - Librerian. How to count the number of this Group. -
How to use javascript variable in django if statement (template)?
I'm trying to update my html element with django if statement: element.innerHTML= `{% if person.name == ${value} %} something {% endif %}` but I receive an error: TemplateSyntaxError at / Could not parse the remainder: '${value}' from '${value}' I also tried: `{% if person.name == ${value} %} something {% endif %}` But the statement doesn't work properly. Is there anything I can do to combine javascript with Django variables? -
Django heroku application wont run
i was deploying a django project this is my prjoect github https://github.com/EpicGL/CM1 im getting this[ 2022-03-25T19:04:21.335972+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=my-cm1.herokuapp.com request_id=8c9ac21d-96a7-4563-80df-8e2c60bd98ea fwd="202.134.14.132" dyno= connect= service= status=503 bytes= protocol=https. 2022-03-25T19:04:22.514399+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=my-cm1.herokuapp.com request_id=bcd22f6d-8ddb-43b0-8a66-5e5c79f0d2d7 fwd="202.134.14.132" dyno= connect= service= status=503 bytes= protocol=https error can anyone please help hi there, i was deploying a django project this is my prjoect github https://github.com/EpicGL/CM1