Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add resizble text area in django_better_admin_arrayfield for Django admin?
I need to add resizable text area instead of textinput for Django admin using django_better_admin_arrayfield library. Model class Activity(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) mood = models.ForeignKey(Mood, on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(upload_to='./activities/images') age = models.CharField(max_length=255) duration = models.CharField(max_length=255) file = models.FileField(upload_to='./activities/files') activity = ArrayField(models.TextField()) tips = ArrayField(models.TextField()) class Meta: verbose_name_plural = 'Activities' Django admin class ActivitiesAdmin(ModelAdmin, DynamicArrayMixin): formfield_overrides = { DynamicArrayField: {'widget': DynamicArrayTextareaWidget} } list_display = ["pk", "title"] -
Sharing a DB between Django ORM & Prisma ORM
I have a Django application thats using Postgresql. At the same time the DB is being used by a Nodejs application (On the Nodejs application the queries to DB are being done using raw sql. For enhanced security I want to use Prisma to handle DB queries on the Nodejs application, I have installed Prisma using npm, next steps are: 3. Run prisma db pull to turn your database schema into a Prisma schema. 4. Run prisma generate to generate the Prisma Client. You can then start querying your database. will number "3" break my current DB?? The DB has models created using Django. I would like my DB to remain readable using Django ORM. I dont wish to write new models or change anything using the Nodejs application (Its only for fetching data from DB) -
Importing a django model into a custom script to save a new model instance
I have a script which parses emails and I wish to save parsed data in the model database. The script is in the django app where the model resides. I've imported the model and wrote the code to create the new model instance. When I run the python module in VSC I get terminal error: **``` django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. ** Other posts on StackOverflow get this far but never solve the problem. I tried importing OS and adding os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') django.setup() To the head of my module. This gets me a new error: ModuleNotFoundError: "No module named 'emails'". This confuses me greatly because I can ctrl+click on the import and it takes me to the appropriate module so it seems to see it, but not recognize the model class Emails(model.Model) within it. I also tried moving the script into the same directory as the models.py file, but had same results. -
How do I resolve Module 'my_project' has no attribute 'celery' error with Docker Compose, Django, Celery?
I can't figure out why celery isn't being recognized. Here is the full error I get when I run docker compose up (excluding everything else that works fine): celeryworker | Usage: celery [OPTIONS] COMMAND [ARGS]... celeryworker | Try 'celery --help' for help. celeryworker | celeryworker | Error: Invalid value for '-A' / '--app': celeryworker | Unable to load celery application. celeryworker | Module 'my_project' has no attribute 'celery' celeryworker exited with code 2 I'm using: Docker version 20.10.23, build 7155243 Django 4.1.7 Python 3.11 Celery 5.2.7 Dockerfile: FROM python:3.11.0 # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # Set work directory WORKDIR /code # Install dependencies RUN pip install --upgrade pip COPY requirements.txt /code/ RUN pip install -r requirements.txt # Copy the Django project COPY . /code/ docker-compose.yml services: db: image: postgres:15.2 restart: always volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres cache: image: redis:7.0.10 restart: always volumes: - ./data/cache:/data rabbit: image: rabbitmq:3.11.8 restart: always ports: - 5673:5673 - 15672:15672 - 25672:25672 #? volumes: - ./data/rabbit/data:/var/lib/rabbitmq - ./data/rabbit/log:/var/log/rabbitmq web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "uwsgi","--ini", "/code/config/uwsgi/uwsgi.ini"] restart: always volumes: - .:/code environment: - DJANGO_SETINGS_MODULE=my_project.settings.production - POSTGRES_BD=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db - cache nginx: image: … -
ColumnForm object has no attribute 'instance'
I’m trying to submit a Column model, but it throws me an error when I clicked a submit button: the error: 'ColumnForm' object has no attribute 'instance' Forms.py: class ColumnForm(forms.Form): class Meta: model = Column fields = ['name', 'selec_type'] Models.py: class Column(models.Model): user = OneToOneFields (settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete= models.CASCADE) Views.py: from django.views.generic.edit import FormView from django.forms import modelformset_factory from .forms import ColumnForm from .models import Column ColumnForm objects has no attribute instance class ColumnCreate(FormView): template_name = 'design.html' form_class = modelformset_factory(Column, form=ColumnForm, extra=30) success_url = '/' def form_valid(self, form): form.instance.user = self.request.user form.save() return super().form_valid(form) def form_invalid(self, form): return self.render_to_response(self.get_context_data(formset=form)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = context['form'] return context <form method='post'> {% csrf_token %} {{ formset.management_form}} {% for form in formset %} {{form.as_p}} {% endfor %} <button type='submit'>Save<button/> <form/> -
Django and Websocket giving an error index: WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/example/' failed:
I am following tutorial on django channels and I am getting an error that I can't solve. In web console this is displayed: index(16): WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/example1/' failed: Here is settings.py: ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } routing.py file on project level: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import anonymous.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( anonymous.routing.websocket_urlpatterns ) ), }) asgi.py: import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = get_asgi_application() routing.py on app level: from django.urls import re_path from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatRoomConsumer.as_asgi()), ] consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) pass and chatroom.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link … -
Response Headers disappear after redirection - Django
I'm connecting an external auth system and a external permission system to my Django application (the auth will only be used in Django Admin and API, while the permission will be used for any request). Both systems are aready integrated and functional. But since this will only be available behind a VPC (which is not ready), my team need a mocked service in order to continue the mobile and frontend development. The mocked services are also using Django (I don't know about the real services because it's all proprietary software). The current flow is: Request hits Django's Admin. It checks if there's a session and if it's valid. If not, it checks for authorization headers (this should be coming from the Auth system) It there's neither, the user is redirected to the Mocked Auth login page. After submitting the login form, if it's valid, it'll redirect the user back to the Admin page, with a HTTP_TOKEN response header When accessing the request.headers in the admin view, there's no HTTP_TOKEN header or any other that contain the information I've just sent. I think this might be some kind of middleware that is overwriting this headers. mocked_auth/views.py class LoginView(LoginView): redirect_authenticated_user = True … -
Django If both product and variant models have color model, how to make Product tells which colors can variant has?
I have 4 models, product, variant and color. class Size(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Color(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=400) colors = models.ManyToManyField(Color) sizes = models.ManyToManyField(Size) class Variant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=10, validators=[MinValueValidator(Decimal('0.01'))]) quantity = models.IntegerField(validators=[MinValueValidator(0)]) color = models.ForeignKey(Color, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) In this example a variant can have 1 product, 1 color and 1 size. The problem is the color and size are chosen among all the colors and sizes in the store. I want to limit the color and size in variant to the options of colors and size that were chosen in Product. If there anyway please let me know. Thank you :) -
Django messages not showing in certain views
I have multiple views in which I would like to show success messages when redirected home page after successful functions are performed. I have all the required settings added. I am rendering the views from a separate app to my main app, but all urls are referenced so there should be no issues there either. So I have no idea. My Registration view seems to render the message fine, but the rest don't. I will link the views below. WORKING def user_register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) Customer.objects.create(user=user,first_name=first_name, last_name=last_name, email=email) login(request, user) messages.success(request, "Registration successful, you are now logged in...") return redirect('home') else: register_form = UserRegisterForm() return render(request, 'registration/register.html', {'register_form': register_form}) NOT WORKING def user_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,"You were successfully logged in...") return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {}) def user_logout(request): logout(request) messages.info(request, ("You were successfully logged out...")) return redirect('home') HTML {% if messages … -
'TimeSlot' object is not iterable in Python Django
I have a list called time_slots. It contains objects of class TimeSlot. When I write return time_slots[0] I get an error - 'TimeSlot' object is not iterable. Can someone please help me with it? models.py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return f'Number: {self.number}, category: {self.category}, capacity: {self.capacity}, advance: {self.advance}, manager: {self.manager}' class TimeSlot(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() def __str__(self): return f'Room: {self.room}, from: {self.available_from}, till: {self.available_till}' views.py def fun1(): # Some code print(time_slots) # [<TimeSlot: Room: Number: 4, category: Regular, capacity: 4, advance: 14, manager: anshul, from: 02:00:00, till: 04:00:00>, <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 02:00:00, till: 05:00:00>] print(time_slots[0]) # Room: Number: 4, category: Regular, capacity: 4, advance: 14, manager: anshul, from: 02:00:00, till: 04:00:00 return time_slots[0] GitHub repo link -
Django Postgres- how to query jsonb[] in django
The model I'm trying to query has a jsonb[] field data and looks like this data = [{"id":"1","name":"abc","place":"def"},{"id":"2","name":"xyz","place":"uvw"}] I tried querying it using the solution listed here How to filter JSON Array in Django JSONField The query I'm running: name = MyModel.objects.filter( Q(data__contains=[{"name":"abc"}]) ) This query returns an empty query set. If I change data to [{"name":"abc"},{"name":"xyz"}] , then this query works How do I make this query work with all the keys in the json object? -
How to modify Python code to allow for more than two accounts in accounts.json file
Pastebin for the entire PY: https://pastebin.com/CiSnwSAv I have a accounts. Json file that works with the PY file, but as soon as I try to add more than 2 accounts in accounts.json, the py file gives me an error. The py file is suppose to paste email into the login page textbox. It does all it is suppose to but as the github repo states, it can work with upto 6 accounts, it doesn't work with 3. I hope my question is precise and understandable. accounts.json file works fine with 2 accounts [ { "username": "MY@gmail.com", "password": "12345678765" }, { "username": "MY@outlook.com", "password": "123213423" } ] and here is the part of the PY file that might me causing the issue def loadAccounts(): global ACCOUNTS if ARGS.accounts: ACCOUNTS = [] for account in ARGS.accounts: ACCOUNTS.append({"username": account.split(":")[0], "password": account.split(":")[1]}) else: try: ACCOUNTS = json.load(open("accounts.json", "r")) except FileNotFoundError: print("Please create an `accounts.json` file and try again.") prPurple(f""" [ACCOUNT] Accounts credential file "accounts.json" created. [ACCOUNT] Edit with your credentials and save, then press any key to continue... """) input() ACCOUNTS = json.load(open("accounts.json", "r")) But as soon as I add more than one account, [ { "username": "MY@gmail.com", "password": "34324214" }, { "username": "MY@outlook.com", … -
How do I change the menu sequence from "left to right" to "right to left" in backerydemo?
I can't change the menu sequence from "left to right" to "right to left"! This is need because our first language is Persian and we must read from right to left! I changed the languge in base.py to "fa-IR" and wagtail cms languges to "فارسی". But it didn't work. -
I recieved an already written django project that has worked previously on another machine but when I try to run it nothing happens
This is what happens PS C:\Users\***\Downloads\zapisy.zip\zapisy\zapisy-old\src\main python manage.py runserver PS C:\Users\***\Downloads\zapisy.zip\zapisy\zapisy-old\src\main> I just opened it in vscode, installed some python packets that were required and that's all I tried outputting any kind of error to file however the file came out empty -
Unable to open port on AWS ec2 instance (despite other ports working)
I'm running an EC2 instance on AWS. I'm running apache out of the standard port 80 without issues, and I have an node.js/Express application running out of port 3000 without issue. I'm trying to open up port 8000 on the machine and I'm not able to connect. I'm attempting to run a Django project from 8000. Locally, on my machine, I'm able to run the Django project. When I use the curl command locally, I get data back: curl localhost:8000 That returns a valid HTML page. When I use the netstat command, it shows that port 8000 is being listened to. If I open a new window and attempt to start Django again when the first one is running, I get an error that port 8000 is already in use. So, it looks like things are running properly on the local machine. So that leads me to believe that there is something incorrect with my AWS set up. However, I set up the ports the same way for 8000 as I did for 3000. Here is a screen shot of the Inbound rules: I did set up port 3000 over 2 years ago, so it's possible I'm missing a step, … -
Django encrypted field in REST API
Good afternoon, I have a complex backend in Django that feeds a C# desktop application with information, throughout an API. At this point of development I will have to store passwords that my C# application will need to apply locally for each user. I want to store them encrypted in my database and somehow send it to my C# app. What is the best approach for that? I found some ideas on how to encrypt and decrypt the data, but I'm not comfortable about sending them decrypted by a web service, even if I use some Token authentication before the request. Should I some how make a parallel script for decrypt in my C# app, regarding my encrypt in django? Thank you in advance. -
Can I automatically generate a hash or other identifier to track DRF contract changes?
I have a Django DRF app and an external service that would like to know when the API contracts have changed in order to manage cache and other contract-related changes. Could I generate a hash or identifier automatically that reflects the changes to any API contracts in the service? It doesn't need to be versioned/sequential, just a kind of checksum on the contracts. Note: I'm not looking for a hash of the API data changing, just the "shape" or contract structure of the API. -
Redis as django cache and celery backend
Can I use same redis instance as both django cache as well as celery backend? Does principle of separation of concern applies here? Would there by any side effect of having them inside same instance? -
How can I access the class attribute name via the class itself to improve readability and type hinting in Python?
Suppose you have the following classes: class MyClass: attribute1: str attribute2: int class MySecondClass: another_attribute1: str another_attribute2: int I want to access the string 'attribute1' via the MyClass class. For example MyClass.attribute1.fieldname, but I am cannot find such an option. If something like this is possible, could you please let me know? I will explain two possible use cases below: Use case 1 Suppose I want to create method which updates an instance of MyClass with an instance of MySecondClass. It should return a boolean indicating whether the instance of MyClass is updated. I would like to put all the fields I want to map in a dictionary so I can loop over them. E.g. my_class_instance: MyClass my_second_class_instance: MySecondClass field_map = { 'attribute1': 'another_attribute1', 'attribute2': 'another_attribute2' } updated = False for field1, field2 in field_map.items(): current_value = getattr(my_class_instance, field1) new_value = getattr(my_second_class_instance, field2) if current_value != new_value: setattr(my_class_instance, field, new_value) updated = True return updated The main issue that I have with this solution is that it does not take advantage of type hinting or the power of my IDE when I refactor this code. If I would rename attribute1 to attribute_one on the MyClass class, the code would break … -
Django with celery in Docker Env
I have confusion whilst setting up django as docker container. Basically there's celery and celery beat. If i understand correctly celery beat is a scheduler so it needs to be only initialised once. So when horizontally scaling using AWS ECS using docker image i can put django and celery inside same image but not celery beat. Is this assumption correct? -
My submit button is not calling the POST function, I do not know why
This is my page2.html file <form method="post" action="/" class="search-div justify-center align-center text-center form" id="form-change" > {% csrf_token %} <label for="contact-owner">Do you want to check an Email or Phone number?</label> <br> <br> <select name="--select--" id="contact-type" required > <option value="">--Select--</option> <option value="email" id="mail">Email</option> <option value="phone" id="phn">Phone No.</option> <option value="sms-o" id="sms">SMS</option> </select> <br> <br> <label for="contact">Enter Contact : </label> <br> <input type="email" class="search" id="contact_number" required> <br><br> <div id="mail-details"> <label for="subject">Enter Subject of Email : </label> <br> <input type="text" class="search" id="subject" name="subject" required="required "> <br><br> <label for="mail-body">Enter Body of Email : </label> <br> <input type="text" class="search" id="mail-body" name="mail-body" required="required "> <br><br> </div> <div id="sms-details"> <label for="sms">Enter SMS recieved : </label> <br> <input type="text" class="search" id="sms" name="sms" required="required "> <br><br> </div> <div id="after-sub" class="active"> <label for="spam-check">Spam</label><br> <input type="text" id="spam-check" required readonly> <br><br> <label for="risk-score">Risk Score</label><br> <input type="text" id="risk-score" readonly> <br> </div> <button type="submit" id="sub">Submit</button> </form> This is my urls.py def page2(request): if request.method == "POST": print("Test2") return render(request, 'page2.html') print("TEST1") return render(request, 'page2.html') Only TEST1 gets printed. I am not able to enter my request.method=='POST' block. I have tried changing the button types and checking for case sensitivity on the off chance that's my error. -
django page doesn't show anything
My djangp page doesn't show anything `{% extends 'base.html' %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href=" {% static '/css/loginstyle.css' %} "> <h2>Giriş Yap</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> <br> {% csrf_token %} <button type="submit" onclick="location.href='http://127.0.0.1:8000/accounts/signup/'">Sign Up`</button> </form> {% endblock content %}` it doesnt work its show anything -
Django Pyhton: Infinit Scroll feed
I'am working on a Social Media Website, I use Django, Python. I would like to make an Infinit Scroll Paginator to have a User-Friendly Surf experience. For now it shows a Select Bar at the end, f.e. 1, 2, 3, Last. How to make an Infinit Scroll Paginator where it laods when you scroll to the end? feed.html {% if posts.has_other_pages %} {% if posts.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{posts.previous_page_number}}">Previous</a> {% endif %} {% for num in posts.paginator.page_range %} {% if posts.number == num %} <a class="btn btn-info mb-4" href="?page={{num}}">{{num}}</a> {% elif num > posts.number|add:'-3' and num < posts.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{num}}">{{num}}</a> {% endif %} {% endfor %} {% if posts.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{posts.next_page_number}}">Load more Shots</a> <a class="btn btn-outline-info mb-4" href="?page={{posts.paginator.num_pages}}">Last</a> {% endif %} {% endif %} views.py @login_required def posts_of_following_profiles(request): profile = Profile.objects.get(user = request.user) users = [user for user in profile.following.all()] posts = [] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.user.post_set.all() posts.append(p_posts) my_posts = profile.profile_posts() posts.append(my_posts) if len(posts)>0: qs = sorted(chain(*posts), reverse=True, key=lambda obj:obj.date_posted) paginator = Paginator(qs, 6) page = request.GET.get('page') try: posts_list = paginator.page(page) except PageNotAnInteger: posts_list = paginator.page(1) … -
How to Django query only latest rows
I have the following Django models: class Amount(Model): hold_fk = ForeignKey(to=Hold) creation_time = DateTimeField() class Hold(Model): group_fk = ForeignKey(to=Group) class Group(Model): pass Each Group has multiple holds and each Hold has multiple amounts. I have a Group instance. I want to get all the amounts that belong to the group, but I only want the latest one from each hold (newest creation time). How do I accomplish that using Django? -
Wagtail filter by related model field in PagesAPIViewSet
I have EntryPage model that have M2M relation to Category (categories field name). I've added viewset for Entries: class EntriesViewSet(PagesAPIViewSet): base_serializer_class = EntryPageWithSiblingsSerializer model = EntryPage body_fields = PagesAPIViewSet.body_fields + EntryPageWithSiblingsSerializer.Meta.fields listing_default_fields = PagesAPIViewSet.listing_default_fields + EntryPageWithSiblingsSerializer.Meta.fields detail_only_fields = ["prev_entry", "next_entry"] Now I want to be able to filter entries by Category's name. Like following: /wt/api/nextjs/v1/blog_entries/?categories__name=name. Is there easy way to do that using existing FilerBackends, or I need to write my own?