Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL keyword argument named "user". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly
I am getting AssertionError in articledetails view. I am getting bellow error AssertionError: Expected view ArticleDetailView to be called with a URL keyword argument named "user". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I want to use RetrieveAPIView to Used for read-only endpoints to represent a single model instance. Where I did wrong? And what is the correct way to fix this? below is my view.py file class ArticleDetailView(RetrieveAPIView): serializer_class = ArticleDetailSerial permission_classes = [permissions.AllowAny] lookup_field = 'user' queryset = ArticleDetail.objects.all() def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): instance = self.get_object() # here the object is retrieved serializer = self.get_serializer(instance) return Response(serializer.data) def get_object(self): """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ queryset = self.filter_queryset(self.get_queryset()) # Perform the lookup filtering. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field assert lookup_url_kwarg in self.kwargs, ( 'Expected view %s to be called with a URL keyword argument ' 'named "%s". Fix your URL conf, or set the `.lookup_field` ' 'attribute on the view correctly.' % … -
Django websocket: Exception inside application: object.__init__() takes no parameters
everyone. I just moved my django project from my former server to my new server. When I tried to run websocket, It returns "Django websocket: Exception inside application: object.init() takes no parameters". But when I went back to my former server to run the project, it was running without any error. Does anyone know the problem it might be? BTW, the django version is 3.1.3 in my new server and 3.1.2 in the former server. Others are the same. detailed error info: WebSocket HANDSHAKING /webssh/ [218.88.113.148:60549] Exception inside application: object.__init__() takes no parameters Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/usr/local/lib/python3.6/dist-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/usr/local/lib/python3.6/dist-packages/channels/sessions.py", line 172, in __call__ return await self.inner(self.scope, receive, self.send) File "/usr/local/lib/python3.6/dist-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/usr/local/lib/python3.6/dist-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/usr/local/lib/python3.6/dist-packages/channels/routing.py", line 160, in __call__ send, File "/usr/local/lib/python3.6/dist-packages/asgiref/compatibility.py", line 33, in new_application instance = application(scope) File "/usr/local/lib/python3.6/dist-packages/channels/generic/websocket.py", line 23, in __init__ super().__init__(*args, **kwargs) TypeError: object.__init__() takes no parameters -
Custom URLs/routes API with Django Rest Framework
I'm trying to make an api according to the teachings of the course, but it is difficult, because I can't customize the urls, it is possible to explain how you do this in the image: Basically I'm trying to pass the plate through the url, but I can only pass the id = ( I wanted that when accessing parking it showed only the license plate and when accessing / parking /: plate it showed the details of the car. But so hard to do something along these lines that I no longer know who to look for. I need help to learn this. Can you just guide me in some way? Thanks! Somebody help me. Almost 1 month trying and nothing 🥺 My code is this, please help me! https://github.com/eltonsantos/parking_control -
Django inline formset won't validate
This is the first time I am using formsets, and it won't validate for some reason. As I understand it, all form fields need to be non-empty for the form to validate. Are there any other conditions? What could be wrong, there are no error messages, the call to formset.is_valid just returns false when I'm expecting it to be true. views.py PhraseMatchFormset = inlineformset_factory(parent_model=Exercise, model=ExercisePhraseMatch, fields=( 'is_active', 'givenPhrase', 'matchPhrase'), extra=4, can_delete=True) formset = PhraseMatchFormset( instance=exercise, initial=initial_dict) if formset.is_valid(): formset.save() Validation function is_valid() is always returning false for some reason. initial_dict output [{'id_exercisephrasematch-TOTAL_FORMS': '4', 'id_exercisephrasematch-INITIAL_FORMS': '0', 'id_exercisephrasematch-MIN_NUM_FORMS': '0', 'id_exercisephrasematch-MAX_NUM_FORMS': '1000', 'id_exercisephrasematch-0-is_active': 'on', 'id_exercisephrasematch-0-givenPhrase': 'oih', 'id_exercisephrasematch-0-matchPhrase': 'buhip', 'id_exercisephrasematch-0-DELETE': 'off', 'id_exercisephrasematch-1-is_active': 'on', 'id_exercisephrasematch-1-givenPhrase': 'oih', 'id_exercisephrasematch-1-matchPhrase': 'biuo', 'id_exercisephrasematch-1-DELETE': 'off', 'id_exercisephrasematch-2-is_active': 'on', 'id_exercisephrasematch-2-givenPhrase': 'uiygv', 'id_exercisephrasematch-2-matchPhrase': 'vyui', 'id_exercisephrasematch-2-DELETE': 'off', 'id_exercisephrasematch-3-is_active': 'on', 'id_exercisephrasematch-3-givenPhrase': 'uyv', 'id_exercisephrasematch-3-matchPhrase': 'vuy', 'id_exercisephrasematch-3-DELETE': 'off'}] models.py class ExercisePhraseMatch(models.Model): exercise = models.ForeignKey(Exercise, default=1, on_delete=models.CASCADE) course = models.CharField( default='', max_length=255, verbose_name="Course Name") lesson = models.CharField( default='', max_length=255, verbose_name="Lesson Name") sequence = models.IntegerField( default=1, verbose_name='Sequence') is_active = models.BooleanField( default=True, verbose_name='Active') givenPhrase = models.CharField( default='', max_length=255, verbose_name="Given Phrase") matchPhrase = models.CharField( default='', max_length=255, verbose_name="Match Phrase") def __str__(self): return('course: ' + self.course + ' lesson: ' + self.lesson + ' exercise no. ' + self.sequence) -
GCP Kubernetes Ingress Unhealthy Service failing
I have a deployment, service, and ingress for a Django application in Google Cloud Kubernetes. When I apply all configuration, ingress fails because the Django service is unhealthy. Below is the configuration. My Django app returns status 200 on "/"; however, when I swapped my image with another, ingress worked fine. So it seems it could be my image which uses Gunicorn, but I can't seem to solve the issue. See the code examples below. Thank you a lot! Django routes # urls.py def index(request): html = "<html><body><h1>API</h1></body></html>" return HttpResponse(html) urlpatterns = [ path('', index), ] Dockerfile FROM python:3.8-slim ENV APP_HOME /app WORKDIR $APP_HOME # Install dependencies. COPY requirements.txt . RUN pip install -r requirements.txt # Copy local code to the container image. COPY ./api . ENV PYTHONUNBUFFERED TRUE k8 deployment # Deployment apiVersion: apps/v1 kind: Deployment metadata: labels: app: api name: api spec: replicas: 1 selector: matchLabels: app: api template: metadata: labels: app: api name: api spec: containers: - name: api image: gcr.io/xxxxx/django-api ports: - containerPort: 8080 protocol: TCP imagePullPolicy: Always command: [ "gunicorn", "--workers", "3", "--bind", ":8080", "--log-level", "INFO", "--timeout", "90", "api.wsgi:application" ] resources: limits: cpu: 50m memory: 2048Mi requests: cpu: 50m memory: 2048Mi k8 service apiVersion: v1 … -
AttributeError: module 'main.views' has no attribute 'home'
I'm making a django project and whenever I run "python manage.py runserver". I see the above error. views.py > from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList, Item Create your views here. def index(response, id): ls = ToDoList.objects.get(id=id) return render(response, "main/base.html", {}) def home(response): return render(response, "main/home.html", {}) main/url.py from django.urls import path from main import views from . import views urlpatterns = [ path("<int:id>", views.index, name="index"), path("", views.home, name="home") ] mysite/url.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), ] Thank you for the help. -
django select related with 3 tables
i have 3 models in django like this: class SlackConfigurationMode(models.Model): MODES = ( ("NORMAL", "normal"), ("ALERT", "alert"), ("DANGER", "danger") ) mode = models.CharField(choices=MODES, default=MODES[0][0], max_length=20) time_send_slack_notification_minute = models.IntegerField(default=0) time_send_slack_notification_hour = models.IntegerField(default=0) description = models.TextField(blank=True) class WebHookConfiguration(models.Model): webhook_url = models.CharField(max_length=100) slack_configuration_mode = models.ForeignKey( SlackConfigurationMode, on_delete=models.CASCADE, related_name='webhook_configurations' ) class MonitorSource(models.Model): TYPES = ( ("FACEBOOK", "facebook"), ("WEBSITE", "website"), ("YOUTUBE", "youtube") ) target = models.CharField(max_length=100) type = models.CharField(choices=TYPES, max_length=20) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey("auth.User", on_delete=models.CASCADE) name = models.CharField(max_length=100) slack_configuration = models.ForeignKey( SlackConfigurationMode, on_delete=models.DO_NOTHING, default=SlackConfigurationMode.objects.filter(mode="NORMAL")[0].id, related_name='monitor_sources' ) i want to get data of webhook_configuration and monitorsource filter by slackconfiguration by mode i use this query: queryset = SlackConfigurationMode.objects.select_related('webhook_configurations', 'monitor_sources').filter( mode='HIGH' ) but have the error: Invalid field name(s) given in select_related: 'monitor_sources', 'webhook_configurations'. Choices are: (none) how can i fix it, and why my query won't work, tks -
Using geodesic in annotate in djnago
I tried to use geodesic in annotate in django to order the fields in model as per distance.Here is my code; from geopy.distance import geodesic from django.db.models import F origin = (some_lat, some_lng) result = model.objects.annotate(distance=geodesic(origin, (F("latitude"), F("longitude"))).kilometers).order_by('distance') #where latitude and longitude are float fields in my model. But it shows an error; TypeError at /tac float() argument must be a string or a number, not 'F' How to do it correctly or is it annotate which doesn't support geodesic. -
No module named 'XXXXXXXX' in Django Heroku deployment
I am looking to make my first HEROKU deploy for django app. I get the following error: Traceback (most recent call last) File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError at=error code=H10 desc="App crashed" method=GET path="/" host=temporalworld.herokuapp.com request_id=facb0a69-8362-4cea-99b1-152866e0487b fwd="146.112.251.213" dyno= connect= service= status=503 bytes= protocol=http looks like i am missing a module. Is anybody familiar with this please? -
How to filter data transaction in created_at > 15 minutes django
How to filter data transaction in created_at > 15 minutes django time_filter = datetime.datetime.now() - timedelta(minutes=15) transaction = Transaction.objects.using(apps).filter( created_at__lte=time_filter, payment_progress__in=['BO', 'ST', 'SC'], email_status__isnull=True ).order_by('-id')[:100] -
How to resolve AttributeError: 'ModelFormOptions' object has no attribute 'concrete_model' in Django
I have been trying to post data in my Django application using ajax post. The data is getting saved but in the terminal I am coming up against the following error: AttributeError: 'ModelFormOptions' object has no attribute 'concrete_model' Here are the relevant codes intended to achieve my goal: Views.py: def saveMaterial(request): if request.is_ajax and request.method == "POST": form = CreateMaterialForm(request.POST) # It's a ModelForm mat_bom_list = CreateBomMatListFormset(request.POST, request.FILES) # Using Inline formset factory if form.is_valid(): form = form.save(commit=False) mat_bom_list = CreateBomMatListFormset(request.POST, request.FILES) if mat_bom_list.is_valid(): form.save() mat_bom_list.save() ser_instance = serializers.serialize('json', [ form, mat_bom_list, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": "Error"}, status=400) else: form = CreateMaterialForm() mat_bom_list = CreateBomMatListFormset() return render(request, "material_create.html", {"form": form, "mat_bom_list": mat_bom_list}) Ajax script: $('#materialListForm').submit(function(e) { e.preventDefault(); var serializedData = $(this).serialize(); console.log(serializedData); $.ajax({ url: "{% url 'material_create' %}", type: 'POST', data: serializedData, success: function() { console.log('Data Saved'); }, error: function (response, status, error) { alert(response.responseText); } }); }); The traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return … -
Django chatroom sends message to another chatroom
I am trying to implement a chatroom consisting of only two users. One user should be present in all chatroom while the other user will be unique to each chatroom. more of like server chatting with one client at time. I am experiencing an issue. what is currently happening in my program is once two user are connected to server it sends all the message to second user (user connected later). I am using memurai as it supports redis API for windows. Here's my consumer.py and two html files trying to communicate to it. Consumer.py import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from channels.generic.websocket import WebsocketConsumer class WebConsumer(AsyncConsumer): global server_conn async def websocket_connect(self, event): server_conn.append(self) await self.send({ "type" : "websocket.accept" }) other_user = self.scope['url_route']['kwargs']['username'] print(other_user) user = self.scope['user'] print(user) await self.send({ "type" : "websocket.send", "text":"Hello World" }) chat_room = str(user) + str(other_user) print(event,' to ', chat_room) self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) async def websocket_receive(self, event): print('recieved', event) print(event['text']) await self.channel_layer.group_send( self.chat_room, { 'type':'chat_message', 'message': str(self.chat_room) } ) async def chat_message(self,event): print('message',event) await self.send({ "type":"websocket.send", "text": event['message'] }) async def websocket_disconnect(self, event): print('disconnected', event) index.html <html> <head> </head> <script> … -
Update and Filtering in Django using Tuple
For example I have a table in MySQL called EmployeeData that has columns Emp_ID, Comp_ID, Status. I want to bulk update the "Status" column using filtering. I have a list of tuples Emp_ID and Comp_ID: id_to_update = [(Emp_ID_1, Comp_ID_1),(Emp_ID_2, Comp_ID_2),...] For example: id_to_update = [(2, 10),(3, 30),...] How to do that in using Python Django? Thanks! -
Django Template Tags
I'm trying to create a link in my site that goes to a user's profile page, but right now when logged in it instead goes to the logged in users' profile page. The link is an author's name and I want it so that when clicked on goes to the authors profile page, instead of the logged in users' profile page. I think the problem is in my url template tag for the link (the first tag in post_index.html ) but I don't know what to do. post_index.html {% for post in post_list %} <article class="media content-section"> <img class= "rounded-circle article-img" src="{{ post.author.profile.profile_pic.url }}"> <div class="media-body"> <div class="article-metadata"> #Here! <a class="mr-2" href="{% url 'profile' %}">{{ post.author }}</a> <small class="text-muted">{{ post.published_date }}</small> </div> <h2><a class="article-title" href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.text }}</p> </div> </article> {% endfor %} views.py @login_required def profile(request): if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f"Your Account Has Been Updated! ") return redirect("profile") else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) return render(request, 'users/profile.html', {"u_form": u_form, "p_form": p_form}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return … -
how to properly set a specific permission in different account type Saleor
This is the if statement for the user, i also want to set a specific permission. if account_type == "orderStaff": existing_account = OrderAccount.objects.filter(user=user).first() if existing_account is None: existing_account = OrderAccount.objects.create( user.userPermissions(OrderPermissions.MANAGE_ORDERS), // not working user=user ) -
How to improve approach on save form
I want to save a form, that gets some data initially set/edited before saving: class ProductCreateView( CreateView): model = Product form_class = ProductForm template_name = "store/create.html" def get_initial(self): return {"remark": "testnote"} def get_success_url(self): return reverse_lazy("index") def form_valid(self, form): self.object = form.save(commit=False) Product.objects.create(name = self.object.name, price = 99, remark = "NOTE",) return HttpResponseRedirect(self.get_success_url()) this works just fine, I have two questions though: I thought I could simply add data with get_initial but this is None when printing self.object.remark in form_valid. is this in general a smart approach? I need a new pk and this way I thought I can avoid guessing one (nogo ...). I was not able to populate the fields in the forms.py. -
Why Django query does not provide correct info
I need to query a data by first_name, last_name and dob. However, in a result view I am getting all names and dob from database; and not specific person. My view.py is: class SearchResulsView(generic.ListView): model = Patient template_name = 'admissions/search_results.html' def get_queryset(self): firstname = self.request.GET.get('firstname', '') lastname = self.request.GET.get('lastname', '') dob = self.request.GET.get('dob', '') object_list = Patient.objects.filter( Q(dob__icontains=dob) & Q(first_name__icontains=firstname) | Q( last_name__icontains=lastname) ) return object_list My form.html is: <form action="{% url 'search_results' %}" method="get"> <input type="text" name="dob" placeholder="dob"> <input type="text" name="firstname" placeholder="first name"> <input type="text" name="lastname" placeholder="last name"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> Here is a search result (all dob's are imaginable and not belong to a particular person): Jose Rodriguez Jan. 22, 1956 Jose Rodriguez Jan. 26, 1958 Jose Rodriguez April 24, 1983 Jose Rodriguez Feb. 22, 1958 Jose Rodriguez Oct. 22, 1979 Jose Rodriguez Sept. 21, 1967 -
Steps to track the time spend on a Page for a Django Project
I am trying to understand how tracking the time spend on a page work. I tried to implement it but got lost so I am looking for a simplified step by step guide to add it to my Django project. I have got the solution from here https://stackoverflow.com/a/28256223/13176726 but I do not know how to implement it. Step 1 Add the following script for all HTML templates: <script src="timeme.js"></script> <script type="text/javascript"> TimeMe.setIdleDurationInSeconds(15); TimeMe.setCurrentPageName("my-home-page"); TimeMe.initialize(); window.onload = function(){ setInterval(function(){ var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); document.getElementById('timeInSeconds').textContent = timeSpentOnPage.toFixed(2); }, 25); } </script> Step 2 I am not sure exactly to place the below code to send the data to the backend to be read in Django Admin to know which user has been spending on each page xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","ENTER_URL_HERE",true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); xmlhttp.send(timeSpentOnPage); I am not sure what are the correct steps and where to place the codes in order to implement users time tracking for each page on my Django Project so I need some guidance in this regard -
how to showing python code inside html template div without process it as a tag code in Django
i want to add hint in my html form text , to let the users use predefined python variable, for example : <div> note : you can use " {{company_name}} " tag in your input text to show the company name ! </div> but the " {{company_name}} " not showing up in html output as a text , i see insted : "" note : you can use " " tag in your input text to show the company name ! "" so how let Django template ignore " {{company_name}} " tag and process it as a text not as a code ? -
How to calculate total working hours in Django?
I created the following model: class Timesheet(models.Model): date = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data") entry = models.TimeField(auto_now=False, auto_now_add=False, verbose_name="Hora Entrada") lunch = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True, verbose_name="Início do Almoço") lunch_end = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True, verbose_name="Fim do Almoço") out = models.TimeField(auto_now=False, auto_now_add=False, verbose_name="Hora de Saída") This is then returned in a table, that has an extra field called "Total Hours", in which I need to calculate the total worked hours. Each entry refers to the same day. And I have the following view: def timesheet(request): c = Timesheet.objects.all() context = {'c': c} return render(request, "tracker/timesheet.html", context) The calculation I need to do is: (out - entry) - (lunch_end - lunch). How can I achieve this? -
How to link a project to Django
I am trying to link a colour detection project with a Django Project, but I don't know how to do it correctly. Here is the function that I am trying to link the colours in the image to Post.colors and I want to make it generated directly once the image is uploaded Here is the models.py: class Post(models.Model): title = models.TextField(max_length=100) design = models.ImageField( blank=False, null=True, upload_to='new designs') date_posted = models.DateTimeField(default=timezone.now) colors= models.TextField(max_length=10,blank=True, null=True) def __str__(self): return self.title def imagecolors(self, *args, **kwargs): img = Image.open(self.design) size = w, h = img.size data = img.load() colors = [] for x in range(w): for y in range(h): color = data[x, y] hex_color_lower = ''.join([hex(c)[2:].rjust(2, '0') for c in color]) hex_color = hex_color_lower.upper() colors.append(hex_color) total = w * h color_hex = [] color_count = [] color_percent = [] df = pd.DataFrame() for color, count in Counter(colors).items(): percent = count / total * \ 100 # Do not make it int. Majority of colors are < 1%, unless you want >= 1% if percent > 1: color_hex.append(color) color_count.append(count) color_percent.append(percent) Post.colors=color_hex print(Post.colors) with the above it showing none in the template: {% for post in posts %} {{ post.colors }} {% endfor %} -
Why is Django object manager returning objects instead of their values?
I have two similar Django models inside an app called 'account' that I create and populate using migrations. When I query the contents of each table, one returns the expected values while the other returns 'objects' and I don't understand why. I start with two models: # models.py class AccountType(models.Model): type = models.CharField(max_length=25) def __str_(self): return self.type class MemberType(models.Model): type = models.CharField(max_length=16) label = models.CharField(max_length=32) def __str__(self): return self.label I populate them with these migrations: # 0001_create_table_accounttype.py class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AccountType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=25)), ], ), ] # 0002_insert_accounttypes.py class Migration(migrations.Migration): dependencies = [ ('account', '0001_create_table_accounttype'), ] operations = [ migrations.RunSQL( sql=[ "INSERT INTO account_accounttype (type) VALUES ('Business');"], reverse_sql=[ "DELETE FROM account_accounttype WHERE type = 'Business';"], ), migrations.RunSQL( sql=[ "INSERT INTO account_accounttype (type) VALUES ('Personal');"], reverse_sql=[ "DELETE FROM account_accounttype WHERE type = 'Personal';"], ), ] # 0003_create_table_membertype.py class Migration(migrations.Migration): dependencies = [ ('account', '0002_insert_accounttypes'), ] operations = [ migrations.CreateModel( name='MemberType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=16)), ('label', models.CharField(max_length=32)), ], ), ] # 0004_insert_membertypes.py class Migration(migrations.Migration): dependencies = [ ('account', '0003_create_table_membertype'), ] operations = [ migrations.RunSQL( sql=[ "INSERT INTO account_membertype (type, label) VALUES ('f', … -
Django admin panel is looking weird after deploy on elastic beanstalk... is expecting a nav_bar css and js files
Hi I just deployed a Django app on elastic beanstalk but just realized that the admin panel layout is broken. After looking in the browser console I have found that is expecting for nav_bar.js and nav_bar.css files. This error does not happen locally, as it is not expecting for those files. I would like to know what could be the reason for this to happen. Thank you in advance! Descriptive image -
Stop Django in Celery from opening new db connections for each task
I have multiple celery worker apps that receive tasks from redis and each task fetches data and/or saves data from/to the database using Django Models. import os from django.conf import settings from django.db import transaction from celery import Celery from .models import MyModel os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'workerapp.settings') import django django.setup() # Example task (I have multiple tasks in my celery each doing similar kind of thing) @app.task(bind=True, name='my_task') @transaction.atomic def my_task(task,model_pk): my_model = MyModel.objects.get(pk=model_pk) my_model.field_1 = True my_model.save() As I have muliple of these workers (6 of them) running at the same time with each having multiple tasks of their own, in many of the workers the following error is logged: fatal: remaining connection slots are reserved for non-replication superuser connections I am assuming for each task it is opening a new database connection. Is there a way to open a connection once and all tasks it receives run in the same connection? Or a better way to do it? By the way, new tasks are constantly being added to redis to be received by workers in shoots of several minutes each, every once in a while. -
customer_user() missing 1 required positional argument: 'create' IN SIGNALS
i have a view and signal called with post_save, it seems it is missing something but I cannot see what... I tried bunch of things... And I don't see the answer to question, there's even a lot of solved on positional arguments missing, but non to help my case. It must be simple enough so I can't see it... from .models import Customer from django.contrib.auth.forms import User from django.db.models.signals import post_save def customer_user(sender, instance, create, **kwargs): if created: group = Group.objects.get(name = 'customer') instance.groups.add(group) Mate.objects.create( user = instance, ) post_save.connect(customer_user, sender=User) Views: ... @unauthenticated_user def registerPage(request): form = CreateUserForm() err = '' if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() return redirect('login') else: err = form.error_messages context = {} return render(request, 'accounts/register.html', context) ...