Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble pushing heroku master (django - conda)
for my django app to heroku. I followed a blog steps religiously but am encountering the below error related to anaconda requirement. Then i tried https://github.com/heroku-python/conda-buildpack, but that didn't work either. Where am i going wrong? What shall be done? anaconda requirement not able -
Generalize API declaration for multiple models
In the process of developing a JWT application with Django I noticed the declaration pattern of the CRUD API View, such as: class Create(generics.CreateAPIView): queryset = <some django model>.objects.all() serializer_class = serializer # <some serializer class> class Read(generics.ListAPIView): queryset = <some django model>.objects.all() serializer_class = serializer # <some serializer class> class Update(generics.RetrieveUpdateAPIView): queryset = <some django model>.objects.all() serializer_class = serializer # <some serializer class> class Delete(generics.DestroyAPIView): queryset = <some django model>.objects.all() serializer_class = serializer # <some serializer class> Considering that my specific project has 7 models that have to have these functionalities, instead of declaring 28 versions of the above classes, I think it would be more elegant if there were a class such as: class Create(generics.CreateAPIView): def __init__(self, model, serializer): self.queryset = model.objects.all() self.serializer_class = serializer super().__init__() class Read(generics.ListAPIView): def __init__(self, model, serializer): self.queryset = model.objects.all() self.serializer_class = serializer super().__init__() class Update(generics.RetrieveUpdateAPIView): def __init__(self, model, serializer): self.queryset = model.objects.all() self.serializer_class = serializer super().__init__() class Delete(generics.DestroyAPIView): def __init__(self, model, serializer): self.queryset = model.objects.all() self.serializer_class = serializer super().__init__() class CRUD: """Base class for CRUD Operations""" def __init__(self, model, serializer): self.create = Create(model, serializer) self.read = Read(model, serializer) self.update = Update(model, serializer) self.delete = Delete(model, serializer) That is followed by those instaciations: … -
Django: ModelMultipleChoiceField is applying underlying model's max_length validator to total length of selected results
I'm using a ModelMultipleChoiceField to allow users to select certain model objects to delete. It works fine when a single object is selected, but when multiple objects are selected then a validation error is triggered: "Ensure this value has at most 50 characters". The 50 character limit is from the underlying model's max_length attribute. I'm not sure why this validation is happening at all since I am selecting existing model objects, and even less sure why they are combining the character lengths of all my selections instead of validating each selection individually. I've also noticed that they are counting approximately 20 extra characters for each object selected when totalling the character length. Any help is appreciated. Here is my code: Model: class Template(models.Model): # Relationships user = models.ForeignKey("users.CustomUser", on_delete=models.CASCADE) # Fields name = models.CharField(max_length=50) description = models.TextField(max_length=250) docx_file = models.FileField(("DOCX File"), upload_to=user_directory_path, validators=[FileExtensionValidator(allowed_extensions=['docx'])]) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) def __str__(self): return self.name Form: class TemplateChoiceDelete(forms.ModelForm): name = forms.ModelMultipleChoiceField(queryset=Template.objects.all()) class Meta: model = Template fields = ['name'] # Limit results to templates owned by the current user def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(TemplateChoiceDelete, self).__init__(*args, **kwargs) self.fields['name'].queryset = Template.objects.filter(user=user) View: (ignore the filter code, that is a … -
Django catch missing manifest exceptions
Every now and then I end up with a missing file after deploy a django project, and I find it one of the hardest issues to debug because I get no logging and no error email, its just dead. I have made a custom 500 error page (followed this answer). Is it possible to show the details of which static file is missing on it? With this error Django fails before rendering a 500 page. Heres a traceback of the error: Traceback (most recent call last): File "/usr/lib/python3.8/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 129, in handle_uncaught_exception return callback(request, **param_dict) File "/home/user/project/src/core/base/views.py", line 236, in error_500_view response = render(request, "core.base/500.html", context=context) File "/home/user/venv/project/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/user/venv/project/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/user/venv/project/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/user/venv/project/lib/python3.8/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/user/venv/project/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) … -
Django Channels: Data Going to the Wrong Socket
I am facing the same issue although the as_asgi method is called in my routing. The data are always sent to the second socket. Channels v3.0 and Django V3.1.2 is in use. routing.py websocket_urlpatterns = [ re_path(WS_PREFIX + r'room/(?P<room_name>\w+)/$', RoomConsumer().as_asgi()), ] asgi.py import routing django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) Local server logs: WebSocket HANDSHAKING /ws/room/2/ [127.0.0.1:63280] WebSocket CONNECT /ws/room/2/ [127.0.0.1:63280] WebSocket HANDSHAKING /ws/room/1/ [127.0.0.1:63288] WebSocket CONNECT /ws/room/1/ [127.0.0.1:63288] consumer.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class RoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'room_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'send_data', 'message': "Message received" } ) # Receive message from room group async def send_data(self, event): # Send message to WebSocket await self.send(text_data=json.dumps(event)) This is how I send data: result['type'] = 'send_data' result['test'] = 'test' layer = get_channel_layer() async_to_sync(layer.group_send)('room_2', result) return HttpResponse(status=202) Is there … -
Multiple APIView Classes in a view.py in django rest-framework
Can we have multiple APIView Classes for different html pages in a view file in Django rest-framework? For example: views.py from rest_framework.views import APIView from rest_framework.response import Response class ABC(APIView): //methods class XYZ(APIView): //methods -
How to use radiobutton value in JS in 'for in if' Django condition?
I start using Chart.js graphic in my Django app. I start from sample line graphic https://jsfiddle.net/mdt86/219hry2s/9/. I have added radio button to be able to switch line graphic based on radio button value. I pass a list in my template (get_data_context) and do a foor loop to get data used in the labels and datastes.data as value for Chart line graphic. But I not able too pass selected country value from radio button in my for loop like this : $("#country").on('click', function () { var selected_country = $('input[name="country"]:checked').val(); }); var libelle1 = [{% for item in qs %}{% if item.country == selected_country %}'{{ item.month }}',{% endif %}{% endfor %}]; I understand django is server side and JS client side Do I need to use an ajax query? -
How can I get user from serializer?
I am trying to override perform_update in my views, get user from serializer and assign it to updated_by in my Category model. class Category(models.Model): name = models.CharField(max_length=80) created_at = models.DateTimeField(auto_now_add = True, null = True) created_by = CurrentUserField() updated_at = models.DateTimeField(auto_now = True, null = True) updated_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name="updated_by") deleted_at = models.DateTimeField(null = True) deleted_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name='deleted_by') class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name def soft_delete(self, deleter): self.deleted_by = deleter self.deleted_at = timezone.now() self.save() serializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = "__all__" views: class CategoryView(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() def get_permissions(self): if self.request.method == "GET": self.permission_classes = (AllowAny, ) else: self.permission_classes = (IsAdminUser, ) return super(CategoryView, self).get_permissions() def perform_update(self, serializer): instance = self.get_object() instance.updated_by = username serializer.save() def destroy(self, request, *args, **kwargs): instance = self.get_object() deleter = self.request.user self.perform_destroy(instance, deleter) return Response(status=status.HTTP_204_NO_CONTENT) def perform_destroy(self, instance, deleter): instance.soft_delete(deleter) -
Django structure with separate models and views in different files and a single application
I'm working with django 3.1.3 and I don't want to have several apps, only one main one and within it several models and views, I have seen some documentation that explains that you must create a folder called models and other views and place their respective files inside. but I am having problems since it does not recognize some modules. Could you guide me with some example code that is from this type of django project. Thanks a lot -
Different nested document structure in Elasticsearch and Django
I'm building directory listing type of website and I am using Elasticsearch 7 to implement search. Website is build on top of Django, using django-elasticsearch-dsl (that uses elasticsearch-dsl under the hood). All my records in the database have the same overall structure, the only differ in one field. This is example code that is used with django-elasticsearch-dsl library to define a document. from django_elasticsearch_dsl.registries import registry from records.models import Record @registry.register_document class RecordDocument(Document): """ Elastic-search index document for records. """ category = fields.KeywordField(attr='category_to_es') exposed_until = fields.DateField(attr='exposed_until') active_until = fields.DateField(attr='active_until') active = fields.BooleanField(attr='active') media_count = fields.IntegerField() url = fields.KeywordField(attr='get_absolute_url') meta = fields.NestedField(dynamic=True) def prepare_meta(self, instance): if instance.category > 5: return {'} return {..} In this case, meta field can contain different properties depending record category. If I simply pass a dictionary into meta field, Elasticsearch stores everything as text. That causes problems down the road when trying to aggregate on nested object. An example of an error I get when simply dumping dictionary to meta field would be following. RequestError(400, 'search_phase_execution_exception', 'Text fields are not optimised for operations that require per-document field data like aggregations and sorting So the obvious thing would be to use proper nested object representation, instead of … -
Django Rest: Check if the user is associated with the correct project
I have 3 Models: Task, User, Project. The relations between them are: The task can only be done by one User, although that User can do many tasks (ForeignKey) The task can only be associated with a single Project, although that Project is made up of several different tasks (ForeignKey) Users can work on different projects at the same time (ManyToMany) class User(models.Model): pass class Project(models.Model): user = models.ManyToManyField(User) class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) My question: Before creating or updating a task, I need to verify if the user is associated with a project he is already working on. I wrote the code below, which is commented so you guys can understand it better, but it doesn't work. Nevertheless, Django is not reporting any errors. @api_view(['POST', 'GET']) #! Restricción aquí (POST) def tasks(request): if request.method == 'GET': task = Task.objects.all() serializer = TaskSerializer(task, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TaskSerializer(data=request.data) #1º Get user ID, Project ID associated with the task. #1º Obtenemos el id del usuario y del projecto a que se asigna la tarea usr_id = task.user_id.all() prjct_id = task.project_id.all() #2º Filter by the Project ID given and Get the … -
How to solve this django webpage issue
I'm new to Django. I created an App called Programador related with another App called Proceso, when I try to run the App Programador in the Admin website shows me the next error: 'builtin_function_or_method' object is not subscriptable 15 {% endif %} 16 </label> 17 <div class="{% if not line.fields|length_is:'1' %} col-auto fieldBox {% else %} col-sm-10 {% endif %} 18 {% if field.field.name %} field-{{ field.field.name }}{% endif %} 19 {% if not field.is_readonly and field.errors %} errors{% endif %} 20 {% if field.field.is_hidden %} hidden {% endif %} 21 {% if field.is_checkcard %} checkcard-row{% endif %}"> 22 {% if field.is_readonly %} 23 <div class="readonly" style="margin-top: 7px;">{{ field.contents }}</div> 24 {% else %} 25 {{ field.field }} 26 {% endif %} 27 <div class="help-block red"> 28 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 29 </div> 30 {% if field.field.help_text %} 31 <div class="help-block">{{ field.field.help_text|safe }}</div> 32 {% endif %} 33 <div class="help-block text-red"> 34 {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} 35 </div> This is the code from Programador: import uuid from django.db import models from core.GestionTareasProgramadas.models.Proceso import Proceso class Programador(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) organizacion = models.CharField(verbose_name='Organización', max_length=100, null=True, blank=True) estado … -
How to display images from other places in django template
I am fairly new in Django and developing a book recommendation system using Django and PostgreSQL. I have my dataset with some field that also keeps corresponding book images URL (not the images itself) where images reside in other places, not in my static files or database. i want to access that images online and display them in my Django template here is how I tried to do but didn't work and doesn't access the image. <img src= {{ book.image_url.url }} style="display:block;" width="100%" height="100%" alt=""> and also tried this: <img src="{{ book.image_url.url }}" style="display:block;" width="100%" height="100%" alt=""> where book is dictionary and images_url is simply a url string for image residing somewhere in the web. can you help me out how to access this string of url on the web and display it on django template ? -
how to get html element by the value given to an attribute jQuery
to a div element inside forloop ,i have given an attribute called 'prod_id',and i have set the value of that attribute to current product id html {% for product in products %} <div prod_id={{product.id}}> ..... </div> <button prod={{product.id}}> {% endfor %} jquery let product = $(button).attr('prod') let fade_prod = $('div[prod_id = product]') fade_prod.fadeOut('slow') in second line of jQuery i want to equate prod_id to the value of product. and i've tried equate but the logic isn't working as expected -
Django project without models and data base
It is possible to build a project in Django without models ? I have a views, templates(html), css and urls. That site is looking very good in a browser. It is a hairdressing salon website. Greetings -
How can I implement incremental wait time for django axes?
I'm looking to implement django axes for brute force protection for my application. I want to implement something like this "lockout for 5 minutes after 5 failed attempts, lockout for 10 minutes after another 5 attempts" Seems like the example in the doc is more straightforward with a fixed wait time, so I want to know if it's possible to implement something like this. -
how can i convert django template code into javascript?
first time i am using javascript. i want to convert django html code into javascript. i also create django rest api. i want to render out api data into template using javascript. without if condition javascript rendering data fine. but i am using some if condition in django template i want to use these condition in javascript but i don't know how can i define these if conditions in javascript side. please can anybody know how can i define it and use it in javascript? and how can i use these link in javascript? {% url 'news-detail' pk=object.pk %} {% url 'prompter-view' pk=object.pk %} {% if request.path == '/rundown-list/' %} index.html <table id="approvedData"> <thead> <tr> <th>ID</th> <th>Story</th> <th>Created By</th> <th>Timestamp</th> <th>Priority</th> <th>Action</th> </tr> </thead> <tbody id="approvedList"> {% for object in data_list %} <tr> <td>{{object.id}}</td> <td><a href="{% url 'news-detail' pk=object.pk %}">{{ object.title}}</a></td> <td>{{object.author.username}}</td> <td>{{object.created_on | naturaltime}}</td> <td> {% if object.story_status == "sn" %} <span class="badge badge-danger">Not Done</span> {% elif object.story_status == "sf" %} <span class="badge badge-warning"> Done</span> {% elif object.story_status == "fr" %} <span class="badge badge-success">Approved</span> {% endif %} </td> {% if request.path == '/rundown-list/' %} <td><a class="btn" href="{% url 'prompter-view' pk=object.pk %}">Prompter view</a></td> {% else %} <td> <div class="table-btns"> <a … -
Django filter a floatfield with a value equals or less
I need to filter all the values of the radius less than the data value but django querys only allows me to check if they are equal How can I implement something like this response =item.objects.filter(radius<data) def home (request , data=None): response =item.objects.filter(radius=data) response_vector=[] for response in response: response_vector.append(response) if len(response_vector)>0: return HttpResponse(response_vector[0].items) else: return HttpResponse(401) I do not want to do something like this: def home (request , data=None): response=[] for x in range(0, data): response.append(item.objects.filter(radius=x)) response_vector=[] for response in response: response_vector.append(response) if len(response_vector)>0: return HttpResponse(response_vector[0].items) else: return HttpResponse(401) -
django-ckeditor richtext content can't display normally in the page
i ran into a problem,i intergrated the django-ckeditor5 in my django admin and it worked.but as i tried to display the content that i saved from the editored,it went wrong. for example,i put a centered image in the content,but it displayed differently. enter image description here in the editor enter image description here how it is displayed i noticed that none of the classes in the html codes generated by the editor is loaded,so i tried to load the styles.css in the django-ckeditor5 static directory,but it didn't work. -
Django- How to hide a button from a superuser or admin but show it to regular or active users
I want to hide a button from a Django Admin or superuser but I want to display it if the user is not an Admin or superuser. How to do it? -
No module named 'fcntl
I am using gunicorn on windows to deploy a Django app to heroku, When I run heroku local. The is the a port of the message error that I get line 9, in 5:50:12 PM web.1 | import fcntl 5:50:12 PM web.1 | ModuleNotFoundError: No module named 'fcntl' [DONE] Killing all processes with signal SIGINT 5:50:12 PM web.1 Exited with exit code null ( Can someone help -
Django Model Manage UNIQUE constraint error in save method
this is with Python 3.8 and Django 3.1.3 I have a model with an unique field class SomeModel(models.Model): name = models.CharField(max_length=200, unique=True) i'm searching a way to automatically change the field value if there is an UNIQUE constraint violation If i create a new instance with name ="kevin" while another instance already exists with the same name ="kevin", it would change the name of the new instance with a suffix when save() is called eg : database is empty >>> foo = SomeModel() >>> foo.name = "kevin" >>> foo.save() # again >>> foo = SomeModel() >>> foo.name = "kevin" >>> foo.save() # and again >>> foo = SomeModel() >>> foo.name = "kevin" >>> foo.save() >>> for foo in SomeModel.objects.all(): >>> print(foo.name) kevin kevin_01 kevin_02 didn't find the way to do this, i suppose i have to override the save method and catch the unique constraint error to do that. any ideas ? Thanks -
How to fetch a csrftoken from a django server?
I'm reconfiguring my CDN and I want to begin caching pages that use csrf tokens for form submission. Currently, I'm submitting the csrf token with javascript in a post request with: axios.defaults.headers.post['X-CSRFToken'] = getCookie('csrftoken') This works pretty well locally and allowed me to remove the csrf tokens from the templates. This obviously will not work if I'm accessing cached pages from the CDN. So is it possible for me to fetch a csrf token from the server using Axios and subsequently set it in a post request? If so how do I do this? An alternative approach would be to disable csrf which I tried already but I couldn't fully disable it. If you are signed into admin csrf protection is automatically enabled even on your frontend forms, I couldn't figure out how to remove this not sure if it's a wagtail or django thing. I'm using Django 2.2 + Wagtail 2.11. -
Apache + Django + Ubuntu, client denied by server configuration
I am trying to run a Django project with Apache in an Ubuntu EC2 server that I got from AWS. I think I got pretty much everything done, I can run it with manage.py runserver and see the project on my public DNS. However, I can't seem to get it to run with Apache. I keep getting a 403 error that says "You don't have permission to access this resource." whenever I try to access it via my internet browser. When I check the error logs, I see the error: AH01630: client denied by server configuration:/home/ubuntu/myproject/swe681server/server/server/wsgi.py Even though I am pointing to the wsgi.py file correctly. My conf file looks like this: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host … -
Recurring For Loop
I have a project where I use nested for loop to filter items, but the result keeps recurring the item which is not supposed to be so. Pls, where did I get it wrong? def order_list(request): orders = Order.objects.all() current_user = request.user user_list = orders.filter(user=current_user.id) success = orders.filter(paid=True) fail = orders.filter(paid=False) return render(request, 'orders/order/order_list.html', { 'orders': orders, 'success': success, 'fail': fail, 'user_list':user_list, 'current_user':current_user, }) html {% for ls in orders %} {% for x in user_list %} {% for od in success %} <div class="card mb-3" style="max-width: 540px;"> <div class="row no-gutters"> <div class="col-md-3"> <img alt="product img" class="card-img" src="..."> </div> <div class="col-md-9"> <div class="card-body" style="position: relative;"> <h5 class="card-title">Product {{ od.id }}</h5> <a href="#" style="position: absolute; top: 5px; right: 5px;">View Details</a> <p class="card-text">Transaction ID</p> <p class="card-text"><small class="text-muted">Delivered at {{od.reference_id}}</small></p> </div> </div> </div> </div> {% endfor %} {% endfor %} {% endfor %} the actual result should be as it is in the screenshot below But I get this; Pls, check the images Thanks.