Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
estou tendo dificuldades com este erro MultiValueDictKeyError
Estou testando o Django para Desenvolvimento WEB no Pycharm, estou me deparando com o seguinte erro: enter image description here Segue Views.py: enter image description here Segue models.py: enter image description here Segue arquivo HTML - detalhe_cidades: enter image description here Segue Proj/urls.py: enter image description here Poderiam me auxiliar neste erro para a resolução do problema ?? -
Django FORM_RENDERER for frontend only
By default Django uses this setting determine where the form widgets come from: FORM_RENDERER = 'django.forms.renderers.DjangoTemplates' As we want all labels removed, and apply some overrides, it was changed to: FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' This all works fine for the frontend. However, it renders the backend unusable as now all labels are removed there as well. My question, how do I get Django to use the original setting for the admin? -
How to set LOGIN_URL variable in Django settings so it doesn't redirect anywhere while not logged in
When trying to access url get_room_messages if user is not logged in @login_required redirects him to: /accounts/login/?next=/get_room_messages (as specified in docs) I want it to do nothing (or redirect to the original url, in this example /get_room_messages). I don't want to hardcode it like @login_required(login_url='/get_room_messages'), ideal solution would be to get somehow original url and pass it into @login_required() decorator. @login_required() def get_room_messages(request): user_id = request.user.user_ID user = get_object_or_404(CustomUser, pk=user_id) Thank you for help! -
uploading image in Django inside a for loop
I wanted show the uploaded image from admin url in my index.html template. so i needed to put a for loop and I got a probelm in image src. setting.py : STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] models.py : class Home(models.Model): image = models.ImageField(upload_to = "static") titr = models.CharField(max_length=200) description = models.TextField() created = models.DateField(auto_now_add = True) updated = models.DateField(auto_now = True) class Meta: ordering = ['created'] def __str__(self): return str(self.titr) views.py : from django.shortcuts import render from .models import Home # Create your views here. def index(request): home = Home.objects.all() context = {"homes" : home} return render(request, 'home/index.html', context) index.html(doesn't work) : {% extends 'main.html' %} {% block content %} {% load static %} {% for home in homes %} <br> <h1>{{home.titr}}</h1> <img src="{% static '{{home.image.url}}' %}" style="width:50%" alt="My image"> <p>{{home.description}}</p> <br><hr> {% endfor %} {% endblock content %} index.html(work but it's not what i want): {% extends 'main.html' %} {% block content %} {% load static %} {% for home in homes %} <br> <h1>{{home.titr}}</h1> <img src="{% static '{{home.image.url}}' %}" style="width:50%" alt="My image"> <p>{{home.description}}</p> <br><hr> {% endfor %} {% endblock content %} -
Save data and show it in one http request Django ORM
I'm working on a little app and I'm stuck with one "error" and maybe someone could help me. So basically what I'm trying to achieve is that I want to update two fields from a model (let's say that I have 5 fields in db) and I'm using SomeData.objects.filter(id=pk).update(data=test, data1=test1) but the idea is that I conclude that is necessary to send two requests from views.py ( first request will update the db and the second one will output data desired). The big question is, how can I achieve this in one single http call? The http method is GET but I'm sure that it doesn't matter. Thanks in advance! -
Django Rest Framework - search_fields - DatabaseError at /chapters/ No exception message supplied
Based on the documentation of DRF search_fields, i have implemented search filter in one of my APIs with Foreign key field. So while searching i am facing this error. Can you guys please help me out to get this issue resolved? This is my Parent Model class Chapter(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256) short_code = models.CharField(max_length=256, blank=True) description = models.TextField(blank=True) start_date = models.DateField(default=None) end_date = models.DateField(default=None) status = models.PositiveIntegerField(default=1) created_by = models.CharField(max_length=256, default=None) this is my child model class ChapterTopicTag(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256, blank=True) parent_id = models.ForeignKey(Chapter, on_delete=models.CASCADE) And this is my viewset class ChapterViewSet(viewsets.ModelViewSet): serializer_class = ChapterSerializer filter_backends = [filters.SearchFilter, DjangoFilterBackend] filterset_fields = ['status'] search_fields = ('name', 'description', 'chpatertopic__name',) Whenever i am calling url like http://localhost:8000/parent/?search=childname It throws me this error which is attached in screenshot -
Cache problems in Django/PyMongo/MongoDB
I have a little Django app that uses PyMongo and MongoDB. If I write (or update) something in the database, I have to restart the server for it to show in the web page. I'm running with 'python manage.py runserver' I switched to the django dummy cache but that didn't help. Every database action is within an 'with MongoClient' statement. -
failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0:failed to read dockerfile: read /va.how do i solve this
On startup, the following error appears. OS win 10. how do i solve this problem? (venv) C:\shop>docker-compose up --build [+] Building 0.1s (2/2) FINISHED => [internal] load build definition from shop 0.1s => => transferring dockerfile: 1.78MB 0.0s => [internal] load .dockerignore 0.1s => => transferring context: 2B 0.0s failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: read /var/lib/docker/tmp/buildkit-mount057531924/shop: is a directory Dockerfile and docker-compose are in the root of the project. dima@DESKTOP-1BLNH42:/mnt/c/shop$ ls Dockerfile account blog cart discount_system docker-compose.yaml favorites loyalty_program manage.py orders projectshop requirements.txt search shop venv Dockerfile: FROM python:3.9 RUN apt-get update -y RUN apt-get upgrade -y WORKDIR /app COPY ./requirements.txt ./ RUN pip install -r requirements.txt COPY . ./src CMD ['python3', './src/manage.py', 'runserver', '0.0.0.0:8000'] docker-compose: version: '3.9' services: rabbitmq: image: rabbitmq restart: always web: restart: always build: context: ./shop ports: - 8000:8000 command: ['python3', './src/manage.py', 'runserver', '0.0.0.0:8000'] depends_on: - pg_db pg_db: image: postgres:14 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: -
Celery_worker fixture in pytest, connection already closed error
I have such pytest structure import pytest @pytest.mark.django_db class TestClass: def test_celery_mht_notification_create(self, celery_worker, user): # some test logic When I use celery_worker fixture, I get such error psycopg2.InterfaceError: connection already closed How to fix that? -
How can I instantiate multiple models on one user button press (Django)?
Design example image Code Snippet I'm trying to put together a CRM sort of website that allows users to create subjects and have tasks listed under them. These tasks all have a red or green circle under each week based on its completion status for that week. The problem is I'm not sure how to piece this all together. I can create a task object and have it be listed under the subject but cant find a way to create multiple completion objects and have each one link in with every task and week to allow the user to check off what they completed. I'd really appreciate if someone could point me in the direction as to how to split up the logic for these models so that I can piece them together. Thank you :D -
Django rest framework returning base64 image URL encoded
I have my viewset that returns a basse64 encoded image in the image variable: with open(f"image_file.jpg" , "rb") as image_file: order.image = base64.encodebytes(image_file.read()).decode('utf-8') The thing is, if this code is executed locally like python script.py it returns the right base64 and I can display it, but this viewset is returning a base64 that's URL encoded. Instead of returning something like NMR//9k=, it's returning NMR/9k%3D%0A. How can I change this? I need the proper base64 encoding to display the image on the front. -
Django Model Objects cannot seen in Django Template
Rendered django model object cannot give any output in template. My Code is: model.py: class MyModel(models.Model): address = models.GenericIPAddressField( max_length=15, verbose_name=_('address') ) Path = models.CharField( max_length=300, verbose_name='path', ) activate = models.CharField(max_length=5, default='off', ) views.py: class MyView(ListView): model = models.MyModel.objects.all()[0] template_name = '../on_off.html' context_object_name = 'obj_list' admin.py: class MyAdmin(admin.ModelAdmin): list_display = ('address', 'Path', ) exclude = ('activate', ) change_list_template = '../on_off.html' on_off.html: {% extends 'admin/change_list.html' %} {% block object-tools %} {% if obj_list %} <form id="on_off_status" method="POST"> <label id="onoff" class="switch"> {% csrf_token %} <input type="checkbox" id="togBtn" value=" {{ obj_list.activate }} "> <div class="slider round"></div> </label> </form> {% endif %} ... In Django model, the system accepts only one object and I want to give to toggle switch button value in template using activate field in MyModel model. But it is not rendered in template, I couldn't get any object data even if I try <h1> {{ obj_list }} </h1>, it turns <h1> </h1> . Any help or suggestion appreciated. -
Not able to open admin site in Django - TypeError
During the development of django-based web application I've encountered a problem. I cannot open the admin site. When I put /admin to the site I get: enter image description here This site says also that the problem is in context.py file that is in my overall global python folder that appeared during the installation. The line in which the problem occurs in context. py says: updates.update(processor(self.request)). I am new here so please let me know if more information is needed. Thank you for your help. -
bootstrap - d-flex keeps changing the width of input fields
I have a page where users can change their password, this was created through modifying the Django reset password page. So, currently I am using d-flex in order to style the input fields in order to change the password, however in the event that the password criteria is not met, an error message is outputted. Unfortunately, the width of these output messages are causing the width of the input fields to change. Can anyone help prevent this? Ideally I need the error messages so the user can identify their mistakes made and I also want the width of these input fields to be of a fixed size. I will include the code used below, alongside some before and after screenshots in the event my explanation was not clear enough. <div class="container" v-for="u in user"> <div class="contentContainer"> <h4>Change Password</h4> <div class="d-flex justify-content-center align-items-center"> <form method="POST"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary mt-3">Save changes</button> </form> </div> </div> Before Screenshot After Screenshot Thank you for your time, Alex -
How to deal with differences in Phone Numbers using Twilio?
Tools Django - Twilio WSP API Context I send a message to my own number as +54 9 (1234) 123456 But when I answer back Twilio receives the msg from +54 (1234) 123456 Problem If I save "+54 9 (1234) 123456" in the database and receive validation from "+54 (1234) 123456" I can't get a match to verify. -
Connecting Mongodb to Django
I try to make a project and I need to connect mongodb to django and I have this error. I looked over all the pages about this error and I think that I did all that stuff and still didn't manage to solve it. Do you know what I need to do? django.core.exceptions.ImproperlyConfigured: 'django' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
How to add foreign-key column to dj-stripe admin?
I would like to add plan names to dj-stripe django admin so I can see a readable name for what each subscription is associated with. Adding "cancel_at" worked, but I can't use the name of a Product from a Plan. In my_app\admin.py I do this: from djstripe.models import Subscription from djstripe.admin import StripeModelAdmin, SubscriptionItemInline ... class SubscriptionAdmin(StripeModelAdmin): list_display = ("plan__product__name", "customer", "status", "cancel_at") list_filter = ("status", "cancel_at_period_end") list_select_related = ("customer", "customer__subscriber") inlines = (SubscriptionItemInline,) def _cancel(self, request, queryset): """Cancel a subscription.""" for subscription in queryset: subscription.cancel() _cancel.short_description = "Cancel selected subscriptions" # type: ignore # noqa actions = (_cancel,) admin.site.unregister(Subscription) admin.site.register(Subscription, SubscriptionAdmin) ... Which produces this error: Subscription has no field named 'plan__product__name' How do I add extra columns in dj-stripe that require foreign key lookups? -
AttributeError: 'NoneType' object has no attribute 'username' Django Rest Serializers POST request
I'm making a post request to the django backend from the react frontend. For this I send a json object But the backend is giving me an error. I have given my serializer data in the form of the below json objects removing the default fields like id, created and updated fields and sent the remaining fields. The POST is not successfull showing the error as mentioned below.. Internal Server Error: /create_message/ Traceback (most recent call last): File "C:\Users\Ajay\Desktop\New folder\Mars\marsgc\main\serializers.py", line 31, in get_messager return obj.messager.username AttributeError: 'NoneType' object has no attribute 'username' The function call at the frontend is: let add_message = async (message) => { await fetch(`http://localhost:8000/create_message/`,{ method: 'POST', headers:{ 'Content-Type':'application/json' }, body:JSON.stringify(message) }) } const new_message = async (e) => { e.preventDefault() const messager = user; const body = message; const room_in = room.id; await add_message({body,messager,room_in}) } A general django rest message object is { "id": 2, "body": "Hi", "created": "2022-02-20T17:41:47.796395Z", "updated": "2022-03-13T17:20:26.949428Z", "messager": "ajay", "room_in": 17 }, My models are class Topic(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Room(models.Model): host = models.ForeignKey(User,on_delete=models.CASCADE,null=True) topic = models.ForeignKey(Topic,on_delete=models.CASCADE,null=True) name = models.CharField(max_length=200) description = models.TextField(blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-updated', '-created'] def … -
Django models not giving href value in html format
My model name is cat I am fetching this in html template using safe just like {{cat.languages|safe}} See my model Here is url in html -
Recreating Django Project - MakeMigrations Error
I recently attempted to recreate an existing Django project consisting of one app. So I started the project under the new name I wanted, made the app, and then manually dragged over the old existing app files from the old project app folder into the new app folder. Both projects are looking identical but when I attempt to do an initial migration on the new project it runs this error django.db.utils.OperationalError: no such table: inventory_register Inventory is the name of the app and Register is the name of one of my models. Am I possibly migrating too much too soon considering i have a lot of forms, signals ect im essentially trying to migrate at once? Also happy to provide anymore info that could help clarify -
to return True when the post has a like from the creator of the post
to return True when the post has a like from the creator of the post how to make such an analog on django user = { 'id': 121 } likes = [{ 'userInfo': { 'id': 121 } }] hasSelfLike = any(like['userInfo']['id'] == user['id'] for like in likes) print(hasSelfLike) models.py class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) def get_hasSelfLike(self): return self.likes.values_list('userInfo_id', 'userInfo__id') #returns always True class Like(models.Model): task_id = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True, related_name='likes', name='taskId') user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') -
django factory boy factory with OneToOne relationship
I am using factory boy to create test factory for my django App. And I have trouve defining my factory because my model has a One-to-One relation with itself. My model looks something like this: class MyModel(models.Model): previous: MyModel= models.OneToOneField( "self", related_name="next", null=True, blank=True ) next: MyModel And my factory looks like this: class MyModelFactory(factory.django.DjangoModelFactory): next = None previous = None But then I can't define properly my model in the test: first_model: MyModel= MyModelFactory() second_model: MyModel= MyModelFactory(previous=first_task) So we can see for second_model.previous we can find first_model. But for first_model.next we have nothing. Well it's obvious cause we didn't put anything inside when we define first_model. However, it's obvious we shouldn't make something like: first_model: MyModel= MyModelFactory(next=second_task) second_model: MyModel= MyModelFactory(previous=first_task) cause the second task has not been defined yet when we define the first model. So I don't know in this case what should I do to have first_model.next = second model and second_model.previous = first_model at the same time. -
ZipFile to File to FileField Django Python
I'm doing a call from a API that give me a zip file with two file in it. I manage to extract the file i need (cause it's a PDF) and now i just can't find a solution to save it in my filefield without creating the file in my pc. with ZipFile(io.BytesIO(response3.content)) as z: # response3 is my response to the API for target_file in z.namelist(): if target_file.endswith('pdf'): z.extract(member=target_file) # that's how i can have acces to my file and know it is a valid PDF # here begin the trick with io.BytesIO() as buf: z.open(target_file).write(buf) buf.seek(0) f = File.open(buf) # File is an import of django.core.files rbe, created = RBE.objects.update_or_create(file=f) With this code i get an error with write of z.open(...).write as below: z.open(target_file).write(buf) io.UnsupportedOperation: write Thanks :) -
Django Channels can't "socket.send" when trying to constantly send data to client from server
I am trying to create a game on django using channels. For that I need server to send data to client after certain amount of time. I managed to achieve it but now I can not socket.send anything back to the server. I am having hard time trying to figure out why is that. What I try to achieve is having server constantly sending the data and receive data from the client to save it to database. Second part being where I am stuck currently. consumers.py from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from channels.db import database_sync_to_async from django.utils.crypto import get_random_string from .models import Model import asyncio import json import random from hashlib import pbkdf2_hmac @database_sync_to_async def get_round(): a = Model.objects.last() return a.round_number class Game(AsyncWebsocketConsumer): async def connect(self): self.connected = True self.room_name = 'gameName' self.room_group_name = 'game_room' await self.channel_layer.group_add( self.room_group_name, self.room_name ) await self.accept() while self.connected: await asyncio.sleep(5) server_seed = get_random_string(length=64) public_seed = random.randint(0, 999999) round = await get_round() hash = pbkdf2_hmac('sha256', bytes(server_seed, 'utf-8'), bytes(public_seed), round) result = int(hash[0:8].hex(), 16) % 15 await self.send(text_data = json.dumps({ 'round_result': result })) async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) self.connected = False async def receive(self, text_data): data = json.loads(text_data) print(data) # … -
Django Test: Incorrect type. Expected pk value, received str
I have a simple model having a foreign key: class Job(models.Model): resource = models.ForeignKey(Resource, on_delete=models.RESTRICT, related_name="resource_jobs") required_resource = models.FloatField(default=0) Here is the viewset: class JobViewSet(ModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer I am writing a test to create this Job object like this. self.detail_url: str = "factory:jobs-detail" self.resource = Resource.objects.create(**self.resource_data) self.job_data = { "resource": self.resource, "required_resource": 20, } def test_create(self) -> None: response: Response = self.client.post( self.list_url, data=self.job_data ) print(response.data) self.assertEqual(response.status_code, 201) Upon running the test I get an error: {'resource': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]} How do I pass this object in this dictionary. Thank you for any help.