Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form not populating with POST data
I'm relatively new to Django so hopefully this is quite a simple issue. I am finding the debugging difficult and perhaps that is part of my problem here. Problem: Django form seems to not be populating with post data. Summary: I have 2 models Entities and Breaks. Breaks has a FK relationship to the entity_id (not the PK) on the Entities model. I want to generate an empty form for all the fields of Breaks. Generating a basic form populates all the empty fields, but for the FK it generates a dropdown list of all PKs of the Entities table. This is not helpful so I have excluded this in the ModelForm below and tried to replace with a list of all the entity_ids of the Entities table. This form renders as expected. class BreakForm(ModelForm): class Meta: model = Breaks #fields = '__all__' exclude = ('entity',) def __init__(self, *args, **kwargs): super(BreakForm, self).__init__(*args, **kwargs) self.fields['entity_id'] = ModelChoiceField(queryset=Entities.objects.all().values_list('entity_id', flat=True)) The below FormView is the cbv called by the URL. As the below stands if I populate the form, and for the FK column entity_id choose one of the values, the form will not submit. By that field on the form template the … -
Nested Regroups with django with some attributes from none regroups
I have a django template that I have implemented regroups in it. I have a problem with how to display some of the attributes from my model into the template in a table. I have a couple of issues to address: How can I display the remaining 4 attributes from the ImplementationMatrix model i.e implementation_status, implementation_summary, challenges, and wayforward to be displayed at the respective columns in the table on the template (index.html) without distorting the layout for each instance of ImplementationMatrix. The last for loop in the templates displays only one item for subactivity while I have more than subactivity for the respective activity. Is there any better way of implementing all this? My Models: class Strategy(TrackingModel): """ Stores all the strategies related to HSSP. """ strategy_name = models.CharField( max_length=255, blank=True, null=True, default="") class Meta(TrackingModel.Meta): verbose_name_plural = "Strategies" def __str__(self): return self.strategy_name class Intervention(TrackingModel): intervention_name = models.CharField( max_length=255, blank=True, null=True, default="" ) strategy = models.ForeignKey(Strategy, on_delete=models.PROTECT) class Meta(TrackingModel.Meta): verbose_name_plural = "Interventions" def __str__(self): return self.intervention_name class Activity(TrackingModel): activity_name = models.CharField( max_length=255, blank=True, null=True, default="") intervention = models.ForeignKey(Intervention, on_delete=models.PROTECT) class Meta(TrackingModel.Meta): verbose_name_plural = "Activities" def __str__(self): return self.activity_name class SubActivity(TrackingModel): subactivity_name = models.CharField( max_length=255, blank=True, null=True, default="" ) activity = … -
How to implement redis on Django
I am trying to implement Redis (redis_data = redis.Redis(host='localhost', port=6379, db=0) in Django. Here I am sharing the code. Anyone, please help me to write this code using the Redis server? def redis(request): if request.method == "GET": c = request.GET.get('c', '') p = request.GET.get('p', 2) l = request.GET.get('l', 20) if c and int(c) > 0: data = h.list(c, int(p), int(l)) count = h.count(c) return sendResponse({'p': int(p), 'l': int(l), 'count': count, 'data': h.filter_fields(data)}) return sendResponse(formatErrorResponse(err, 'required')) -
Manage.py unknown command
I am a student and my profesor needs me to install Django on PyCharm. I made a big folder called PyCharmProjects and it includes like everything I have done in Python. The problem is that I made a new folder inside this PyCharmProjects called Elementar, and I need to have the Django folders in there but it's not downloading. I type in the PyCharm terminal django-admin manage.py startproject taskmanager1 (this is how my profesor needs me to name it) After I run the code it says: No Django settings specified. Unknown command: 'manage.py' Type 'django-admin help' for usage. I also tried to install it through the MacOS terminal but I don't even have acces the folder named Elementar (cd: no such file or directory: Elementar) although it is created and it is seen in the PyCharm. -
Replit Django No such file or directory: "common-passwords.txt.gz"
here I have an simple TO-DO app with Django which I created following this tutorial https://www.youtube.com/watch?v=llbtoQTt4qw , on my pc everything is working fine on the localhost, but when I upload and run it on Replit , then try to register a new username, I get this error shown on the image. >>>IMAGE<<< I am using Django register form, nothing additional. In Replit files menu I cant see that directory, so from the terminal I accessed to it with cd/filedirect and created the file there, then the registry form worked, but when I turned off and on the app, I guess it recreates the virtual environment which leads to the missing file again, I updated Django in the Replit terminal and it doesnt help, so what else could be the problem that this file is not genereted whenever the virtual env. is started ? Full info of error: https://drive.google.com/file/d/1CuoT3NZ18Nb0EhHa4sQrCK-CpOfhU9ar/view?usp=share_link I searched info about the problem, tried different solutions but non of them worked for me. -
Django, Redis and Image caching to improve scalability
So I'm working with EC2 and S3bucket and Redis cluster. The idea is that the image gets stored in the cache and gets retrieve from the cache before going to my S3bucket which is very demanding. I can cache and retrieve already, as I've tried just caching the S3 image url. All good till here, but that does not make the response any faster or at least not visibly faster. So the solution here is to store the image itself and this is how I'm doing it. def get_description(self, obj): image_key = f"category_img_ccc{obj.pk}" image_b64 = cache.get(image_key) if not image_b64: illustration_image = obj.description if illustration_image: image_url = illustration_image.url response = requests.get(image_url, stream=True) image = response.content image_b64 = base64.b64encode(image) cache.set(image_key, image_b64, None) if image_b64: return image_b64.decode("utf-8") else: return None And the frontend should then encode it and render this correct ? The response though looks very ugly as you can imagine the decoded image is a quite long char string. Is this the way to go? Can anyone shine some lights in this regard please. -
Changed the model to UNIQUE and form broke
I had a working form and page with following code: model.py class TrafficSources(models.Model): name = models.CharField('name', max_length=250) token = models.CharField('token', max_length=250) def __str__(self): return self.name def get_absolute_url(self): return reverse('ts_detail', kwargs={'slug': self.name.lower()}) Views.py @login_required(login_url='/') def settings(request): error = '' if request.method == 'POST': pk = request.POST.get('id') new_form = TrafficSourcesForm(request.POST) print('new_form here:/n', new_form) if new_form.is_valid(): if pk: TrafficSources.objects.filter(id=pk).update(**new_form.cleaned_data) error = f'{error} Saved.' else: new_form.save() error = '1 new object added.' return redirect(request.path, {'error': error}) else: error = 'Something went wrong!' new_form = TrafficSourcesForm() forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()] return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error}) HTML.html {% for form in forms %} <form method="POST" class="table-row"> {% csrf_token %} <input type="hidden" name="id" value="{{ form.instance.pk }}"> <div class="table-cell">{{ form.name }}</div> <div class="table-cell">{{ form.token }}</div> <div class="table-cell"><button class="btn-success w-100 form-control">Save</button></div> </form> {{ form.non_field_errors }} {% endfor %} <div class="table-row"> <span colspan="3">Add new traffic source:</span> </div> <form method="POST" class="table-row"> {% csrf_token %} <span class="table-cell">{{ new_form.name }}</span> <span class="table-cell">{{ new_form.token }}</span> <span class="table-cell"><button class="btn btn-lg btn-success w-100">Add</button></span> </form> As I need the 'name' column in my table to create URL for django I made this change in my model class: class TrafficSources(models.Model): name = models.CharField('name', max_length=250, unique=True) token = models.CharField('token', max_length=250) I've med … -
MAC M1 pro - Encountered error while trying to install libsass package
× Encountered error while trying to install package.╰─> libsass ERROR: Couldn't install package: libsass -
Django, django-ckeditor-5. Delete media files after deleting the pages
everyone! I use django with django-ckeditor-5enter link description here. Users make his artickes, upload images in this editor. How delete images from article, when article is deleted. django-cleanup doesn't solve that problem, because in deletes only images stored in separate field, but in the case of django-ckeditor-5, images are stored in the field "article_text" -
django translation ngettext not working with gettext in the same file
this is my setup to generate translations for both singular and plurar text from django.utils.translations import ngettext as _ from django.utils.translations import gettext num = 3 my_plural_string = _("{num} apple", "{num} apples", num).format(num=num) my_single_string = gettext("this is a text") When using ngettext and gettext in the same file the generated .po file doesn't include the msgid_plural attribute for the first string #: .\test_app\test_translation.py:10 msgid "{num} apple" msgstr "" #: .\test_app\test_translation.py:11 msgid "this is a text" msgstr "" -
Why does the Python Secrets module keep generating the same passwords in this function in Django
Here is the function: def generate_password(): alphabet = string.ascii_letters + string.digits + "!@#$%^&*()+=/.," return ''.join(secrets.choice(alphabet) for i in range(12)) I added this to a Django model, so that it is automatically called when creating a user, and automatically generates its password. This is the code in the model: password = models.CharField(max_length=100, default=generate_password()) For some reason, creating 4 users is always going to create at least one duplicate password, if not two. this is an example of the passwords generated by creating 7 users: PpN(ky^tabgP iIS@4gfe@7sc 6#oNlIH0MbQg 6#oNlIH0MbQg iIS@4gfe@7sc PpN(ky^tabgP PpN(ky^tabgP This approach was suggested by different people and documentation, yet it seems like this function is always cycling between only a few passwords, and keeps repeating them. Can anyone help me understand why and how to avoid it? Django needs to be restarted some times so adding passwords to a set is not convenient. -
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 …