Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
database application to use in Django
I'm confused to select which db should i use in Django and what db is mostly used for Django to develop small or medium or large applications? What is the best database application to use in Django projects and Why ? help me regarding this. -
Access Django Rest API using Azure access token and SimpleJWT access token
Need just hint, tried all possible ways. Any approach is highly appreciated. Problem statement: access jwt authenticated django rest api using azure ad access token in postman and local app. django app is hosted on azure app service. Challenge: pass two token with different header values in authorisation header such that azure token is also reader with django jwt token. A. All possible authorisation in postman. B. Different authorization keys and header values in django jwt settings I've deployed my django application on azure app service. I'm using JWT authentication for all rest API's. I've an azure directory and service principal linked to azure web app. In postman, I can get access token from azure active directory(using clientID, Secret, resource, etc.) and use the same token to call django rest api. I can easily access unauthenticated API just by using azure access taken in authorization bearer header. For JWT authenticated API, I'm not able to use them (crud operation) as none of my approach is working. Azure access token header value : Bearer Django JWT token header value: Bearer, Token, JWT. -
How to allow 'filter' query parameter Django REST Framework JSON API?
I am using Django REST Framework with djangorestframework-jsonapi When I query with filter[name]=THEOS DRF raise an error into my browser. I tried to query with this URL http://localhost:8000/api/space_objects/?filter[name]=THEOS THe other parameter from JSON API I can use it without any problem. ValidationError at /api/space_objects/ [ErrorDetail(string='invalid filter[name]', code='invalid')] And this is my DRF JSON API settings DRF JSON API Documentation REST_FRAMEWORK = { 'PAGE_SIZE': 10, 'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler', 'DEFAULT_PAGINATION_CLASS': 'rest_framework_json_api.pagination.JsonApiPageNumberPagination', 'DEFAULT_PARSER_CLASSES': ( 'rest_framework_json_api.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework_json_api.renderers.JSONRenderer', # If you're performance testing, you will want to use the browseable API # without forms, as the forms can generate their own queries. # If performance testing, enable: # 'example.utils.BrowsableAPIRendererWithoutForms', # Otherwise, to play around with the browseable API, enable: 'rest_framework_json_api.renderers.BrowsableAPIRenderer' ), 'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata', 'DEFAULT_SCHEMA_CLASS': 'rest_framework_json_api.schemas.openapi.AutoSchema', 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_json_api.filters.QueryParameterValidationFilter', 'rest_framework_json_api.filters.OrderingFilter', 'rest_framework_json_api.django_filters.DjangoFilterBackend', 'rest_framework.filters.SearchFilter', ), 'SEARCH_PARAM': 'filter[search]', 'TEST_REQUEST_RENDERER_CLASSES': ( 'rest_framework_json_api.renderers.JSONRenderer', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'vnd.api+json' } My model class SpaceObject(models.Model): class Meta: ordering = ['norad'] norad = models.IntegerField(primary_key=True) object_type = models.CharField(max_length=200, null=True) name = models.CharField(max_length=200, null=True) period = models.FloatField(null=True) inclination = models.FloatField(null=True) apogee = models.FloatField(null=True) perigee = models.FloatField(null=True) rcs_size = models.CharField(max_length=200, null=True) tle_1 = models.CharField(max_length=200, null=True) tle_2 = models.CharField(max_length=200, null=True) last_updated = models.DateTimeField(max_length=6, default=timezone.now) My serializer class SpaceObjectSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SpaceObject fields = ['norad', … -
Exception Value: 'CustomUser' object is not callable | CustomUserModel
I am trying to create a custom user model. The model is working fine in command prompt and I am able to login to admin panel as well. I can access Login page as well. But when I try to access the SignUp page Is is showing me the following error. Error image models.py from django.db import models from django.contrib import auth from django.urls import reverse # Create your models here. # for custom user from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, User from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): '''Model representation for user''' user_type_choices = ( ('ps','problem_solver'), ('pp','problem_provider') ) account_type_choices = ( ('o','Organization'), ('i','Individual') ) user_type = models.CharField(max_length=5, choices=user_type_choices, default='pp', verbose_name="Who you are? ") account_type = models.CharField(max_length=5, choices= account_type_choices, default='o', verbose_name="Account Type ") email = models.EmailField(max_length=50, unique=True, blank=False, verbose_name="Your Email ") is_active = models.BooleanField(default=True) # anyone who signs up for thsi application is by default an active user is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # the person who has highest level of control over database # need to specify manager class for this user objects = CustomUserManager() # we are not placing password field here because the password field will always be required REQUIRED_FIELDS = ['user_type', 'account_type'] USERNAME_FIELD … -
Error : 'cryptography' package is required for sha256_password or caching_sha2_password auth methods
I try to connect to my admin page of my django site which is online, but I get the error that I put on the title, and yet the connection passed yesterday, I tried to install the package with : $ python3 -m pip install PyMySQL[rsa] and I have the answer: Requirement already satisfied -
please, I have an AttributeError bug to fix, Please, help me out
I created an address project in my Django project which works fine but I want to the program to avoid users from viewing their billing address and update address page if they have not created an address yet. This is the views of the code that runs well: views.py def register_address(request): instance = "" try: if request.method == "POST": form = AddressForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "You have successfully added a shipping address!") return redirect('address:billing_address') except: pass return render(request,'address/register_address.html',{'form':form}) def billing_address(request): address = "" try: address = UserAddress.objects.get(user=request.user) except: pass return render(request,'address/billing_address.html',{'form':address}) def update_address(request): form = UpdateForm() try: if request.method == "POST": form = UpdateForm(request.POST) if form.is_valid(): address = UserAddress.objects.get(user=request.user) address.user = request.user address.country = request.POST.get("country") address.state = request.POST.get("state") address.area = request.POST.get("area") address.city = request.POST.get("city") address.street_name = request.POST.get("street_name") address.save() messages.error(request, "You have successfully updated address.") return redirect('address:billing_address') except: pass return render(request,'address/update_address.html',{'form':form}) urls.py urlpatterns = [ path('register_address/',views.register_address,name="register_address"), path('billing_address/',views.billing_address,name="billing_address"), path('update_address/',views.update_address,name="update_address"), ] register_address.html <h2>Register Adress</h2><br> <form action="" method="POST" onsubmit="myButton.disabled = true; return true;"> {% csrf_token %} {{form.as_p}} <input type="submit" class="btn btn-success" name="myButton" value="Submit"> </form><br><br> <button class="btn btn-primary" onClick = "window.location= '{% url 'address:bi lling_address'%}';">View Billing Address</button> <button class="btn btn-secondary" onClick = "window.location= '{% url 'address:update_address' %}';">Update Address</button><br><br> … -
Functions under django model class
I'm working on django models. At the design level I'm confused if I can implement functions inside model class. If I can implement then what kind of functions should be going inside and what kind of functions shouldn't. I couldn't find a document regarding this apart from doc Or is there any document where I can figure out about this? -
How can I recover previous versions of a file on HoloLens2?
I have an app which creates and writes in a csv file. With some error, the app overwrote the file which had all the log data from the past, and now I have got a new file with only recent data on. I want to restore the older version of the csv file, but HoloLens2 doesn't give me the options to do so like a normal Windows computer. Is there anyway that I can recover previous version of the file on HoloLens2? The file wasn't on OneDrive or any other cloud locations. The property of the file doesn't give me any access to the previous versions. The settings of HL2 doesn't seem to have file recovery options either. -
How can I run my django application using HTTPS Protocol on the Local machine
I am trying to load my local site using the HTTPS protocol instead of the insecure http. I have used RunServerPlus extension package of the Django Extensions. I have installed the Django Extensions, the Werkzeug, and pyOpenSSL. When I load the runserver_plus --cert-file cert.crt, the mysite.com does not load at all. Could someone help me here please? Here is the django-extensions installed INSTALLED_APPS = [ # ... 'django_extensions', ] Here are the ALLOWED_HOSTS[] ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1'] -
django is not responding urls.py file
I am writing basic views and then putting it in urls.py but it is still not working. views.py [from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("hello how are you") project urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), ] apps urls.py from django.urls import path from . import views urlpatterns = [ path('home/',views.home,name='home') ] I have also included my app in settings of project (Installed apps). -
How to check user for 2 fields from another model with ManyToMany fields
How am i suppose to check request.user for 2 fields in the same time I want to show different pages in header if user is customer or contractor by another many to many field or if he is contractor and customer in same time show both pages Im not sure how am i suppose to do that Models.py: class CounterParty(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) name = models.CharField(max_length=150, verbose_name='Name') customer = models.BooleanField(default=False, verbose_name='customer') contractor = models.BooleanField(default=False, verbose_name='contractor') counter_user = models.ManyToManyField(User, blank=True, related_name='counter_user') views.py: @login_required def home_view(request): counter_party = CounterParty.objects.all() context = { 'counter_party': counter_party } return render(request, 'common/home.html', context) header.html: {% for counter in counter_party %} {% if request.user in counter.counter_user.all %} <li class="nav-item"><a class="nav-link" href="{% url 'contractor_view' %}"><span class="nav-link-title">Contractor</span></a></li> {% endif %} {% endfor %} {% if request.user.is_staff %} <li class="nav-item"><a class="nav-link" href="{% url 'admin:index' %}"><span class="nav-link-title">Admin</span></a></li> {% endif %} -
How to Enable check-in when clicked and at the same time checkout will be enabled and vice versa using JavaScript?
I am working on a project where I need to develop the attendance part using Django and JS (as main languages) and I'm stuck with an issue that after clicking check-in button it does not get disabled and the user can check-in multiple time that will cause error when checking out because of the Database. This is what I tried using Javascript but failed.. <script> const button1 = document.querySelector('.checkin'); const button2 = document.querySelector('.checkout'); button1.onlclick = function () { document.cookie = "button1=disabled; button2=enabled; expires=Fri, 31 Dec 9999 23:59:59 GMT"; }; button2.onclick= function () { document.cookie = "button1=enabled; button2=disabled; expires=Fri, 31 Dec 9999 23:59:59 GMT"; }; window.onload = function () { const cookies = document.cookie.split("; "); cookies.forEach(function (cookie) { const [key, value] = cookie.split("="); if (key === "button1" && value === "disabled") { button1.disabled = true; button2.disabled = false; } else if (key === "button1" && value === "enabled") { button1.disabled = false; button2.disabled = true; } }); }; </script> This is what I tried using Django Template language but failed. {% if items.check_in is none %} <script type="text/javascript"> const button1 = document.querySelector('.checkin'); const button2 = document.querySelector('.checkout'); button1.disabled = false; button2.disabled = true; </script> {% else %} <script type="text/javascript"> const button1 = … -
Unable to connect django conatiner with postgresql conatiner
I am trying to connect django and postgresql inside docker container I am unable to do that I have tried couple of things but nothing works for me following is my docker compose file version: '3.8' services: backend: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/app restart: on-failure depends_on: rabbitmq: condition: service_healthy postgres: image: postgres container_name: postgres volumes: - ./postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=main - POSTGRES_USER=postgres - POSTGRES_PASSWORD=admin ports: - 5431:5431 rabbitmq: image: rabbitmq:3-management container_name: rabbitmq hostname: rabbitmq ports: - 15673:15672 environment: RABBITMQ_DEFAULT_USER: guest RABBITMQ_DEFAULT_PASS: guest healthcheck: test: rabbitmq-diagnostics check_port_connectivity interval: 30s timeout: 30s retries: 10 # queue: # build: # context: . # dockerfile: Dockerfile # command: 'python consumer.py' # depends_on: # - db # - rabbitmq # - backend In settings.py I have configuration like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'main', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'postgres', 'PORT': '5431' } } Now when I run docker-compose up command I get the error "django.db.utils.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution" I also tried by changing host name to localhost in settings.py it then gives me this error "TCP/IP connections on port … -
Django Rest Framework - How can I check if a value is in an array of related field objects?
I have a post model and it has likes (responses). I would like to see if the logged in user has already liked a post and so I need to check if the id of the logged in user matches any of the users that liked a post. Here is the post model: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1, related_name="posts") body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=video_directory_path, null=True, blank=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] get_latest_by = "created_at" def __str__(self): return self.body[0:30] def get_absolute_url(self): return self.slug def one_image(self): return PostImage.objects.all().filter(post=self)[:1] Here is the Post Response (like) model: class PostResponse(models.Model): like = "like" feelings = [ (like , "like"), ] response = models.CharField(max_length=15,choices=feelings, default=like) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="responses") user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ['post', 'user'] verbose_name = "Post response" verbose_name_plural = "Post responses" db_table = "post_responses" def __str__(self): return str(self.response) Here is the Post Response serializer and it works kind of because there is only one post response. How can I check if the user id … -
Reducing the number of queries in a Django TabularInline Admin
I have an admin with 1 row in the tabular inline. I have a custom queryset in class ExtensionTabularInlineFormSet(BaseInlineFormSet): def get_queryset(self) -> QuerySet[Extension]: qs = super().get_queryset() This gets called 20 times to display that one row. When you have more rows, it gets called 20 times/row (I think, but I lose count). The culprit is calls to this method: def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if not self.is_bound: return len(self.get_queryset()) return super().initial_form_count() The solution would be to cache this value, but admin views seem like singletons way too often for this to work. How do I solve this? -
Django model choices and jQuery DataTables sort
I am struggling to get a sorting to work in jQuery DataTables when I want to sort objects based on choices in the django model. With the snippets included I can sort it based on the values 1..n in choices, but as it considers those as strings, sorting is not working properly. It considers 10, 11 and 12 to be lower that everything between 2 to 9. How would I fix this issue? I have this model in my django app: class Action(models.Model): STATUS_CHOICES = ( ('1', 'Status 1'), ('2', 'Status 2'), ('3', 'Status 3'), ('4', 'Status 4'), ('5', 'Status 5'), ('6', 'Status 6'), ('7', 'Status 7'), ('8', 'Status 8'), ('9', 'Status 9'), ('10', 'Status 10'), ('11', 'Status 11'), ('12', 'Status 12'), ) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default=1, verbose_name='Status') From views I will render everything to my template: def actions_view(request, *args, **kwargs): actions = Action.objects.all() context = { 'actions':actions, } return render(request, "actions.html", context) And in the template everything will be displayed in jQuery datatables: <table id="actionTable" class="table table-striped"> <thead> <tr> <th>Action</th> </tr> </thead> <tbody> {% for action in actions %} <tr> <td><span style="display:none;">{{ action.status }}</span>{{ action.get_status_display }}</td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready(function () { $('#actionTable').DataTable({ fixedHeader: … -
How to listen a django web api from celery task?
I created a project using Django, Celery, and celery beat for scheduling tasks. I created a task using celery. @shared_task(bind=True) def my_task(self): # How can I listen if a post API is requested from here? return "Task Successful" I want this task to listen to a web API if it is requested. Is it possible? -
Where to run Celery on AWS
In my django web app I am running a calculation which takes 2-10 minutes, and the AWS server times out with a 504 server error. It seems that the best way to fix this problem is to implement a worker, and offload the calculations. Through some research, it seems that Celery with a Redis server (maybe AWS SQS instead?) are best for Django. However, I only see tutorials for instances that are run locally. The Redis server is hosted by Railway and Celery is run in a separate terminal than Django. I'm curious if/where Celery and Redis should be running on AWS. This answer says you should try to run celery as a deamon in the background. AWS Elastic Beanstalk uses supervisord already to run some deamon processes. So you can leverage that to run celeryd and avoid creating a custom AMI for this. It works nicely for me. but don't the Celery and Redis servers still need to run somehow? Where does the Celery server run? How do I start it? How can I leverage supervisord to run daemon processes? The documentation isn't helping me very much with AWS integration -
Django Rest Framework - How do I get the count and average of a related field in a serializer
I have a post model that can have ratings: Here is the post model: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1, related_name="posts") body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=video_directory_path, null=True, blank=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] get_latest_by = "created_at" def __str__(self): return self.body[0:30] def get_absolute_url(self): return self.slug def one_image(self): return PostImage.objects.all().filter(post=self)[:1] and here is the post rating model: class PostRating(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="ratings") score = models.IntegerField(choices=list(zip(range(1, 6), range(1, 6)))) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user rating" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "post rating" verbose_name_plural = "post ratings" db_table = "post_ratings" def __str__(self): return str(self.score) Here is the serializer: class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True, required=False) class Meta: model = Post fields = [ "id", "category", "body", "images", "video", "ratings", "published", "created_at", "updated_at", ] depth = 1 def create(self, validated_data): user = User.objects.get(id=self.context['request'].data.get('user')) category = Category.objects.get(id=self.context['request'].data.get('category')) new_post = Post.objects.create(**validated_data, category=category, user=user) images = dict((self.context['request'].FILES).lists()).get('images', None) if images: for image in images: PostImage.objects.create( image=image, post=new_post ) return new_post QUESTION: … -
django rest framework returning incorrect format for response
I'm having issues with serializing a list. so my models.py looks like this: class Show(models.Model): name = models.CharField(max_length = 500) rating = models.FloatField() network = models.CharField(max_length = 500) description = models.CharField(max_length = 500) episodes = models.IntegerField() cast = models.CharField(max_length=200) rating = models.FloatField() def __str__(self):return self.name and my serializers.py looks like this: class show_serializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only = True) name = serializers.CharField() network = serializers.CharField() description = serializers.CharField() episodes = serializers.IntegerField() cast = serializers.ListField(child=serializers.CharField(max_length=100)) rating = serializers.FloatField() def create(self, data): return Show.object.create(****data) however my json response is formatted wrong, I'm trying to make it { "id": 3, "name": "Breaking Bad", "description": "A high school chemistry teacher diagnosed with inoperable lung cancer turns to manufacturing and selling methamphetamine in order to secure his family's future.", "network": "AMC", "episodes": 62, "cast": [ "Bryan Cranston", "Aaron Paul", "Anna Gunn", "Dean Norris" ], "rating": 9.5 } whats happening is the "cast" part of the json is splitting the cast into multiple characters. for instance it's becoming "cast": [ "[", "'", "B", "r", and so on for every character ] I've tried switching to JSONField, using a ListField for cast in the serializer.py file, using Textfield() for cast in the models -
How to override django local Installed app in saleor platform
enter image description here Hello here are some locally installed app in saleor platform. Now I have to make chnages (override) some codes inside this apps. what are the best practices or how can i do without in disturbance in existing code. Thanks I have tried to overide by following blog But got no result. -
django_crontab no encuentra Template
Utilizo el crontab para verificar datos, y depende la confirmación me envié un correo, utilizo la misma funcion de enviar correos dentro de las views y funciona correctamente, pero al usarlo dentro del crontab, me arroja un error de 'django.template.exceptions.TemplateDoesNotExist' Creo que podría ser un error de la ruta, pero no estoy seguro como debería hacerlo. El error completo: error Funcion que envia los correos: def send_email_pago_premium(cant, url, email, user, fecha_inicio, fecha_fin): print("Enviando email...") try: server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) server.ehlo() server.starttls() server.ehlo() server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) #Construyendo el mensaje mensaje = MIMEMultipart() mensaje['From'] = EMAIL_HOST_USER mensaje['To'] = email mensaje['Subject'] = 'Pagamento Concluido' content = render_to_string('paginas/email/email_pago_premium.html', { 'user': user, 'cant': cant, 'url':url, 'fecha_inicio':fecha_inicio, 'fecha_fin':fecha_fin }) mensaje.attach(MIMEText(content, 'html')) server.sendmail(EMAIL_HOST_USER, email, mensaje.as_string()) print("Email enviado") except Exception as err: print(f"Unexpected {err=}, {type(err)=}") raise -
How i get views.py variable to js file?
views.py def somefunction(request): var = True return render(request, dasboard.html) myfirst.js function myFunction() { } How i get var from views.py into the myfirst.js function? Thank you! -
how to do an if to check if a date is between two dates. Python
I need to check if a certain date is between the month of February, but I can't use year, only month and day. How can i do this using if and else in python? -
#Django How to fetch data with permissions.IsAuthenticatied in views.py using Postman?
I'm trying to fetch data with my Django Restframework API endpoints. This is my UserViewSet in views.py: class UserViewSet(viewsets.ModelViewSet): queryset = PortalsUser.objects().all().order_by('name') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] So this will need the user to login first to view the user information. I tried to GET my user on Postman, and this is the my Postman configuration I'd like to know am I doing it correctly? Should I input my username and password like this? Thanks for your help!