Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No validated date returned by serializer
I get all the devices from a user and pass them to my serializer. He should return a supplier in validated data, but doesn't. Probably because I give more objects than one. How do I get validated data if I give more than one object? view: serializer_class = AdminSiteDevicePatchSerializer serializer = serializer_class( devices, many=True, data=request.data, partial=True, ) serializer.is_valid(raise_exception=True) serializer: class AdminDeviceInfoSerializer(AdminDeviceSerializer): class Meta(AdminDeviceSerializer.Meta): fields = AdminDeviceSerializer.Meta.fields + [ "supplier", ] def to_representation(self, device): data = super().to_representation(device) if not device.supplier: data["supplier"] = None data["supplier"] = SupplierSerializer(device.supplier).data return data -
I don't know why the url is not found
I have added a new action to the MeView called slack_user. But the api is not working and it says not found 404 error. from rest_framework.views import APIView class MeView(APIView): """ 認証ユーザー /users/me/ /users/me/slack_user/ """ serializer_class = MyUserSerializer def get(self, request, *args, **kwargs): serializer = self.serializer_class(request.user, context={'request': request}) return Response(serializer.data) def put(self, request, *args, **kwargs): serializer = self.serializer_class(request.user, request.data, context={'request': request}) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) @action(methods=['get', 'post', 'delete'], detail=True) def slack_user(self, request, *args, **kwargs): obj = request.user ... if request.method == 'GET': slack_user = obj.get_slack_user() return Response({}) if request.method == 'DELETE': obj.slack_users.all().delete() return Response(status=status.HTTP_204_NO_CONTENT) urls.py urlpatterns = [ path('login/', views.LoginView.as_view()), path('me/', views.MeView.as_view()), ] /users/login and /users/me/ work but /users/me/slack_user says not found. could you please help me with this error? -
Websocket Disconnecting channels
I'm trying to run a program based on django channels. After connecting through the browser I receive such messages. Is it Redis' fault or consumers.py?enter image description here -
How to setup separate server for celery periodic tasks?
I am having an issue with celery, so I want to know how to set up a separate server for Celery periodic tasks. As I have one application in Django hosted on AWS, so I want that ec2 instance to handle APIs only not to run periodic tasks. django celery python So can you please share your knowledge on same how to setup separate server for celery periodic tasks? Any help would be highly appreciated. Thank you. -
Autocomplete with specific values in Django for entry field
I am new in Django and want to make the entry field to be autfilled by productname when a user enters productcode (model Products). the below is my code: models.py class NM(models.Model): name = models.CharField(max_length=150) class Products(models.Model): productcode=models.CharField(max_length=200) productname=models.CharField(max_length=500) forms.py class NMForm(forms.ModelForm): name = forms.CharField(max_length=150) class Meta: model = NM fields = ('name',) views.py def home(request): if request.method == "POST": form = NMForm(request.POST) if form.is_valid(): for_m = form.save(commit=False) name = for_m.name template.html {% block content %} {% if user.is_authenticated %} <form method="POST" > {% csrf_token %} {{ form}} <button type="submit">OK</button> </form> {% endif %} {% endblock content %} I know that Django has inbuilt autocomplete.I researched and found some info but they does not work for me. I tried so far to enter the below code in template.html {% for field in form.visible_fields %} {{ field.errors }} {{ field }} {% endfor %} However it does not work. It does nothing. I would appreciate your help and any advice. -
Need Suggestion(Django Permissions) [closed]
I'm developing web application using django. Admin panel provide by django is enough good for development purpose. For the reason of simplicity, I want to transform django model permission in tabular format but I do not have sufficient idea that how to achieve this.enter image description here -
How to align card images in bootstrap 4.4 so that all the cards have equal width and height.?
So basically while making a simple website with Django and bootstrap 4.4 I came up with this issue. I was using 'cards' to add images of books in a grid format like in a bookstore web application. But the cards are not having equal dimensions. How to align card images in bootstrap 4.4 so that all the cards have equal width and height while keeping it responsive to the window size change.?? html <div class="container"> <div class="row"> {% for book in object_list %} <div class="col s3"> <div class="card"> <img class="img-fluid" src="{{book.book_image}}" alt=""> <div class="card-body"> </div> </div> <p class="text-white">{{book.name}}</p> </div> {% endfor %} </div> </div> and .css body{ background: white url('images/webbg.jpg') no-repeat center center; background-size: cover; } -
Should I use both Django views and Rest Framework together and how?
I will create a web app that mostly depends on basic CRUD operations but may change in the future (like getting data from another web service). I also will create a mobile app for my web app as well in order to do the same CRUD ops and the mobile app will use the REST API of my web app. So the question is that which way should I follow to accomplish these plans? Should I first create the REST API and then use it in my regular Django templates? Or should I create both the Django template views (CBVs, i.e. CreateView, UpdateView, DeleteView, ListView) and also REST API views separately? I really confused as I don't know what people do for such apps. Can you help me to have a roadmap? What would you do and why? -
How to send file (docx) to the user end so that user can download that file in django?
Please check the image File is located in the main project directory where the manage.py file is located ? -
Merge 2 models (tables) in Django and show it in my template
I have 2 models one defines all the all the devices that I have, and the other stores the information that the devices are obtaining. The code of they is the following, class Device(models.Model): dev_eui = models.CharField(max_length=16, primary_key=True) producer = models.CharField(max_length=20, blank=True, null=True) model = models.CharField(max_length=20, blank=True, null=True) firmware = models.CharField(max_length=10, blank=True, null=True) dev_name = models.CharField(max_length=20, blank=True, null=True) description = models.CharField(max_length=40, blank=True, null=True) fixed = models.BooleanField() dev_lat = models.FloatField(null=True, blank=True) dev_lon = models.FloatField(null=True, blank=True) deco_name = models.CharField(max_length=20) fleet_id = models.IntegerField(null=True, blank=True) class DevData(models.Model): data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False) data_id = models.IntegerField() dev_eui = models.CharField(max_length=16) gateway = models.CharField(max_length=25) data_timestamp = models.DateTimeField() rssi = models.IntegerField() snr = models.IntegerField() datarate = models.CharField(max_length=15) frequency = models.IntegerField() seq = models.IntegerField() data_1 = models.FloatField() data_2 = models.FloatField(null=True, blank=True) data_3 = models.FloatField(null=True, blank=True) data_4 = models.FloatField(null=True, blank=True) data_5 = models.FloatField(null=True, blank=True) data_6 = models.FloatField(null=True, blank=True) data_7 = models.FloatField(null=True, blank=True) Actually what I want is show a table in my template, combining all the data from devData and adding the dev_name and fleet_id from devices. Now what I'm doing is obtaining all the data and in the template filtering it. But I'm sure it's better and easier doing this in the views.py, but I don't know how. Reading … -
Django REST Framework, different serializers in same GenericView
I have a question regarding using only 1 view or end-point to make multiple requests. We have a url defined as path('ap/', APIndex.as_view()) where we'd like to both get all our AP models as well as create a new one. We have checked the link here, mostly the answer where Mohammad Masoumi mentioned the get_serializer_class method and the use of generic views. This has not worked however as we get the following error message when doing a simple GET request on the above URL. AttributeError at /ap/ 'APIndex' object has no attribute 'action' This occurs in our views_ap.py file in the get_serializer_class method. I have not been able neither to print the self to see what object I had in there. You'll find below our views_ap.py and serializers_ap.py: views_ap.py: from rest_framework import generics from ..models.model_ap import AP from ..serializers.serializers_ap import * from ..serializers.serializers_user import * class APIndex(generics.ListCreateAPIView): """List all ap, or create a new ap.""" # serializer_classes = { # 'get': APIndexSerializer, # 'post': UserIDSerializer, # # ... other actions # } queryset = AP.objects.all().order_by('id') # mapping serializer into the action serializer_classes = { 'list': APIndexSerializer, 'create': APCreateSerializer } default_serializer_class = APIndexSerializer # Default serializer def get_serializer_class(self): print(self) return self.serializer_classes.get(self.action, … -
Django full text search: how to match multiple words in the query
I'm using SearchVector to search all the occurences of a query string contained at least in one of the fields of MyModel. I'm doing this way using icontains: # search_fields is the list of MyModel fields MyModel.objects.annotate( search=SearchVector(*search_fields), ).filter(search__icontains=query) and if I have: m1 = MyModel(foo='foobar', bar = 'bar', baz = 'baz') m2 = MyModel(foo='fooooo', bar = 'barooo', baz = 'bazooo') m3 = MyModel(foo='fooxxx', bar = 'barxxx', baz = 'bazxxx') This works fine if my query is a single word. E.g., foo returns m1, m2, m3 aro returns m2 But I have problems if the query contains more than one word. Indeed: foo bar returns nothing instead of m1, m2, m3 aro azo returns nothing instead of m2 Is there a way to use Django Full Text Search to achieve what I need? -
Django App not connecting to RDS since SSL/TLS Cert Updates
I have a Django app running on ELB connecting to a MySQL RDS db. I checked recently and its no longer working (application is up fine but I get the following error when I try and deploy or run any manage.py db related commands. I can connect to the RDS DB manually without a problem. django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '****.eu-west-1.rds.amazonaws.com' (110)"). I believe this is to do with the recent updates to SSL/TLS certificates - however I've gone into my RDS dashboard and updated to the new 2019 version there and I'm still getting this error. Does anyone know what might be causing this? It worked fine before the cert change so I can only assume it's related. I've tried adding the ssl-ca rds-ca-2019-root.pem to the DB options in django but still get the same error regardless. Any help would be super appreciated as I'm pretty stumped currently. Thanks! -
Class.objects in django
So here is my code def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) This is my model for my Django project class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) and here is the error Class 'Question' has no 'objects' member -
How to get data from Ajax request and change the HTML according to this?
I have tried to make an ajax request for getting the background task status but I cannot get the data. Here is my Ajax request; var ii=setInterval(function() { $.ajax({ type: "get", url: '{% url "data:status" %}', success:function (data) { console.log(data) } }); }, 5000); function Cii(){ clearInterval(ii) } Here is my HTML; <div class="jumbotron text-center" id="status"> <div id="display_status"> {% if pending and running %} <p>{{pending}} Waiting.</p> <p>{{running}} Going on.</p> {% else %} {% if completed >= 0 %} <a href='#'> It's done, press for make prediction!</a> {% else %} <p>0 Waiting.</p> <p>0 Going on.</p> {% endif %} {% endif %} </div> </div> Here is the function which is triggered from ajax request; def get_process_status(): now = timezone.now() pending_tasks = Task.objects.filter(run_at__gt=now) running_tasks = Task.objects.filter(locked_at__gte=now) completed_tasks = CompletedTask.objects.all() connection.close() return len(pending_tasks), len(running_tasks), len(completed_tasks) And here is my view; @login_required(login_url = "user:login") def process_status_view(request): if request.is_ajax(): pending, running, completed = get_process_status() context = { "pending": pending, "running": running, "completed": completed, } return render(request, "pending_page.html", context) return render(request, "pending_page.html") How can I fix this? -
Reduce number of queries generated by Django ORM
I have below models class Order(models.Model): .... class Component(models.Model): line = models.ForeignKey( Line, on_delete=models.CASCADE, blank=True, null=True, related_name="components", ) ... class Detail(models.Model): line = models.ForeignKey( "Line", on_delete=models.CASCADE, blank=True, null=True, related_name="details", ) order= models.ForeignKey(Order, on_delete=models.CASCADE, related_name="details") ..... class Line(models.Model): .... **Serializer** class ComponentSerializer(serializers.ModelSerializer): qty = serializers.SerializerMethodField(read_only=True) def get_qty(self,component): return (component.qty)-sum( map( some_calculation, Detail.objects.filter( line__components=component,order__active=True) ) ) I have a list view using model viewsets def list(self, request): queryset = Order.objects.filter(order__user=request.user.id,active=True) serilizer = OrderSerializer(queryset,many=true) The component serializer is used inside the order serializer. My question is the query inside the ComponentSerializer hits every order record. If my understanding is correct is there any way to reduce this -
How to create model object via model mommy for inherited model in django?
I have a model which is inherited from Django User model. class CustomUser(User): ... How to create the model object using model mommy library? -
Custom AuthenticationForm never called
I am using custom authentication form to validate user name in Django. I following the process mentioned in link CustomAuthenticationForm. But class CustomAuthenticationForm or confirm_login_allowed never called after I press login button. Could you please let me know if I am missing anything. I am using Django 1.6.10. -
Javascript not executing with Django when file called from js block
I am trying to execute a simple javascript command on a project with Django and manage to do so from inside the HTML template but not when I import the javascript via a js block. What could be the reason ? In more detail, the JS is this : console.log("test"); document.querySelector('#js-table').style.height = "50px"; It works if i include it at the bottom of the HTML, wrapped between two <script> tags. But if i add at the bottom of the html template: {% block js %} <script src="{% static 'app/js/basic.js' %}"></script> {% endblock %} and run the same JS command, the console prints test and returns document.querySelector(...) is null -
django wsgi setup with settings subfolder
I'm trying differents environment settings for my project, below is my project folder structure: |-app |-project |-settings |-base.py |-dev.py |-prod.py |-urls.py |-wsgy.py In base.py, how can i setup WSGI_APPLICATION django settings variable to point wsgi file on parent folder ? base.py: WSGI_APPLICATION = 'project.wsgi.application' The error is: django.core.exceptions.ImproperlyConfigured: WSGI application 'project.wsgi.application' could not be loaded; Error importing module. Thanks in advance. -
what does "about:blank#blocked" error mean when using Django?
So I'm a beginner in Django. And whenever I try to access a page via tag in my template, I get the error. so below is my views.py def ArticleDetail(request, authuser_id, slug): thisArticle = myArticle.objects.get(slug=slug) return render(request, 'article/detail.html', {'thisArticle' : thisArticle}) urls.py urlpatterns = [ # some other urls path('article/<int:authuser_id>/<slug:slug>', views.ArticleDetail, name='ArticleDetail') ] And my html file that has all the articles listed {% extends 'main/base.html' %} {% block title %} DANSANG {% endblock %} {% block content %} {% for item in allArticles %} <!--allArticle is the instance that brings all objects(articles)--> <h1><a href="{{item.url}}">{{item.title}}</a></h1> <h2>{{item.url}}</h2> <h4>{{item.created}}</h4> <h4>{{item.modified}}</h4> <p>{{item.contents}}</p> {% endfor %} {% endblock %} I'm not sure if this is enough information you need. I've never seen the "about:blank#blocked" error, so I'd like to know what this error means. I appreciate your help :) -
django how to join two models with same fields
class plan(models.Model): baseyear = models.DateField() baseline = models.TextField() targetyear = models.DateField() target = models.TextField() frequency = models.ForeignKey(Frequency, on_delete=models.CASCADE) duration = models.ForeignKey(PlanDuration, on_delete=models.CASCADE) sectorresponsible = models.ForeignKey(Sector, on_delete=models.CASCADE) kpi = models.ForeignKey(Kpi, on_delete=models.CASCADE) class Performance(models.Model): plan = models.ForeignKey(Plan1, on_delete=models.CASCADE, blank=True, null=True) performance = models.TextField() report = models.FileField(upload_to='file/',null= True,default='not provided') year_of_performance = models.TextField(blank=True, null=True) kpi = models.ForeignKey(Kpi, on_delete=models.CASCADE,blank=True, null=True) how to join these models through target year and year_of _performance with similar values -
How to update a post using form wizard in Django
I have created a multipage form using the form wizard from the form tools package and it works. I am trying to create and update view so that I can be able to update the created post. I have tried using generic update view, this only display the page without the form. Then, I tried using the same code for the create view by using a get method but this seems not to work also. I will appreciate it if someone can point me in the right direction. Thanks. views.url class FormWizardView(SessionWizardView): template_name = "new_rental.html" form_list = [NewRentalPropertyForm, NewContractForm] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'images')) def done(self, form_list, **kwargs): rentalproperty_instance = RentalProperty() contract_instance = Contract() for form in form_list: rentalproperty_instance = construct_instance(form, rentalproperty_instance) contract_instance = construct_instance(form, contract_instance) rentalproperty_instance.save() contract_instance.rentalproperty = rentalproperty_instance contract_instance.save() return redirect('mini_rental:property_list') class UpdateWizardView(SessionWizardView): template_name = "update.html" form_list = [NewRentalPropertyForm, NewContractForm] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'images')) def done(self,pk, form_list, **kwargs): rentalproperty_instance = RentalProperty.objects.get(pk=pk) contract_instance = Contract() for form in form_list: rentalproperty_instance = construct_instance(form, rentalproperty_instance) contract_instance = construct_instance(form, contract_instance) rentalproperty_instance.save() contract_instance.rentalproperty = rentalproperty_instance contract_instance.save() return redirect('mini_rental:property_list') form. html Update rental listing {% load i18n %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form method="post"> {% csrf_token %} <table> {{ wizard.management_form }} … -
How can set time range field in dajngo model
In Django model field has TimeField for store time but how can I store Time Range like start_time & end_time ? Is there any model field in django to do this job ? for example working_in_time = models.TimeRange(start_time, end_time) -
Migration dependencies reference nonexistent parent node when trying to migrate after db change
Before, I used to keep the same db for development and production (postgresql). This isn't the greatest idea, so I made it so that the db I was currently using would only be used in production (and I'd have an sqlite db locally). Well, I tried to migrate the production db and hot this traceback when trying to migrate at heroku: (bosnetvenv) michael@michael-VivoBook-ASUSLaptop-MJ401TA:~/projects/znet/bosnet$ heroku run python manage.py migrate › Warning: heroku update available from 7.35.0 to 7.38.1. Running python manage.py migrate on ⬢ zealchain... up, run.1153 (Hobby) /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 79, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 267, in build_graph raise exc File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 241, in …