Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how fetch seperate data from multiselectfield in django ORM?
I use in product model, below code : SIZE_CHOICES = ( ('4x3', '4x3'), ('2.5x3.5', '2.5x3.5'), ('2x3', '2x3'), ('1.5x2.25', '1.5x2.25'), ('1x4', '1x4'), ('1x3', '1x3'), ('1x2', '1x2'), ('1x1.5', '1x1.5'), ('50x100', '50x100'), ('50x85', '50x50'), ) and size = MultiSelectField(choices=SIZE_CHOICES, default='4x3') when I use below code : {{product.size}} the template show all size blow by blow, like this : 4x3, 2.5x3.5, 2x3, 1.5x2.25, 1x4, 1x3, 1x2, 1x1.5, 50x100, 50x50 How can I access to any data on one field in multiselectfield by django template ? -
Django ModelViewSet Method \"DELETE\" not allowed even when providing ID in the URL as required for detail views
I am using ModelViewSet for a CustomUser(AbstractBaseUser) model. Every other action is working except Destroy. This is my URL: router.register(r'profile', UserDetailView, basename='user_detail') As per the DefaultRouter() convention, I'm using this URL:127.0.0.1:8000/api/auth/profile/f7b5bcbe-7c92-494d-a3a2-a07e686b6e63/ with 127.0.0.1:8000/api/auth/ as the prefix. The authorization token is in its header. Here, I'm using UUID field as the ID field. When I'm calling the URL with DELETE method in postman, it's returning: { "detail": "Method \"DELETE\" not allowed." } I don't understand what is wrong here! Generally this message is shown if an ID is not provided in the URL for the detail view. But, here I'm providing ID. What is wrong here? -
nginx seems to be writing files in collect_static/CACHE every minute
I've a django website set up using gunicorn + nginx + memcached. Not sure when it started, but I'm finding new css and js files in .../collect_static/CACHE/css and .../collect_static/CACHE/js every minute, like output.2fde5b60eff0.css. These new files are owned by root www-data, unlike the original files that are copied from development to production after running collectstatic which are owned by the user id used to copy the files. I use django.contrib.staticfiles.storage.ManifestStaticFilesStorage. I have no clue if this is normal, or because of some misconfiguration. But in every few days, I need to clean the server because of this. Any suggestions what is going on here? -
how change django's validation error in html
When I submit a form and want the required error to appear when I submit a blank field, I get another error message, specifically "answer", how do I delete it? html is like this -> <ul class =" errorlist "> <li> answer <ul class =" errorlist "> <li> This field is required. </li> </ul> </li> </ ul>. image I found the options in google but it did not work i want only "This field is required." Thanks in advance models.py from django.db import models from django.core.exceptions import ValidationError class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions", blank=True) answer=models.CharField(max_length=100, null=True) def __str__(self): return str(self.questin) views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question,Answer import random from django.forms import modelformset_factory def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): questions=Question.objects.all() form=AnswerForm() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): ques=request.POST.getlist("question_id") ans=request.POST.getlist("answer") for i in range(len(ques)): form=Answer(questin=Question.objects.get(id=ques[i]), answer=ans[i]) form.save() return redirect(request.path) return render(request, "question/ans.html", {"form":form, "questions":questions}) ans.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> <form method="POST" novalidate> {% csrf_token %} {% for question in questions %} <input … -
error while executing python manage.py makemigrastions
My Models Are: from django.db import models Create your models here. class ExamCenter(models.Model): cname=models.CharField(max_length=70) city=models.CharField(max_length=60) class Student(ExamCenter): name=models.CharField(max_length=60,default=False) roll=models.IntegerField(default=False) when i Type python manage.py it generate an error but i cannot find it. the error is You are trying to add a non-nullable field 'examcenter_ptr' to student without a default; we can't do that (the database needs something to populate existing rows). 2.remember It is a Multitable inheritance. -
different procfile for Heroku and Aptible
I have this situation. I have a django project which is hosted in Heroku (Staging app) and Aptible( Production app) as well. My question is, is it possible to have separate procfile in a single project or something that tells when deploy to Heroku and when deploy to Aptible. I am using CircleCi for CI/CD. PS: following line only works for Aptible: web: NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-program gunicorn --access-logfile=- --error-logfile=- --bind=0.0.0.0:8000 --workers=1 --preload myapp.wsgi whenever I have to deploy to Heroku, I have to edit procfile as following, otherwise it gives Application Error: web: gunicorn myapp.wsgi Any suggestions will be appreciated. -
Why are exceptions not showing in Django Channels' AsyncHttpConsumer handler?
I'm using Django 2.2.10 with channels 2.3.0. I have a consumer.py that looks like this: from channels.generic.http import AsyncHttpConsumer import json class LongPollConsumer(AsyncHttpConsumer): async def handle(self, body): await self.send_headers(headers=[ (b"Content-Type", b"application/json"), ]) print("Raising exception...") raise Exception("ERROR") print("Exception raised") await self.send_body(json.dumps({"status": "all good"}).encode("utf-8")) When I run Django, and connect to the URL with my browser, the Django logs show "Raising exception...", and then they stop. No traceback of the actual exception. Makes development hard if I can't see any exceptions. Is there a way to make them appear? -
Django Rest Framework browsable API breaks when changing the port
I'm currently developing my first app with DRF and I'm pretty impressed by it and the browsable API it has build in. However, when I change the port where I host my application (both in manage.py aswell as in the runserver command), all the buttons stop working. I can still click on links to make sure resources where created, but that's about it. I also can't log in and the POST forms don't appear, which is really the most annoying part. Moreover, when I change the port back to the default 8000, it's still broken. Don't really know if I can post an example of this. It doesn't seem to depend on anything in the actual code. It just happens when I change the port. -
django ForeignKey in for loop
i will like to show data in table from two models with ForeignKey: i will use this models as example: class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ['headline'] and now i will like to have dataTable showing all Reporters last_name , and latest Article headline related to each Reporter -
Issue formatting a list of dictionaries to be used by javascript
I'm fairly new to Django, and I'm looking for the ideal way to handle data queried from GraphQL and creating HTML elements from the data to display on my website. I've been generating a list of dictionaries from product information, all of which have "id", "name", "price", etc. and passing them onto my template as is. On the template I can traverse the list with a for loop and the items correctly display within a element as {'id': '...', 'title': '...' } However on js what I see is a string containing [{'id':... What's the ideal way to generate a list of dictionaries usable by JS from this string? -
Django - make tasks in a Ptolty dictionary
I have a projects application, and each project has associated tasks (name, deadline and status) and I want to send this data to a Plotly dictionary to print a gantt in the template my views.py class projectdetail(DetailView): model = Project template_name = 'project_detail.html' slug_field = 'slug' def get_context_data(self, *args, **kwargs): context = super(projectdetail, self).get_context_data(**kwargs) '''Rescatar todos las tareas del pryecto''' project = self.get_object() progress_field = project.todo_set.all() print(progress_field) '''Gantt''' df = [dict(Task="Job A", Start= datetime.date.today().strftime("%Y-%m-%d"), Finish='2021-02-28', Resource='True'), dict(Task="Job B", Start= datetime.date.today().strftime("%Y-%m-%d"), Finish='2021-04-15', Resource='False'), dict(Task="Job C", Start= datetime.date.today().strftime("%Y-%m-%d"), Finish='2021-05-15', Resource='True'), ] colors = { 'True': '#00AA88', 'False': '#BB105A' } gantt = ff.create_gantt(df, colors=colors, index_col='Resource', bar_width=0.3) div = opy.plot(gantt, auto_open=False, output_type='div') context['graph'] = div return context my template.py <li> <span style="color:#bb105a">.Gantt </span> </li> {% if graph %} <div> {{ graph|safe }} </div> {% endif %} how can I convert the list of tasks that I get with progress_field = project.todo_set.all() into a dictionary in df? -
Why my images is not showing in heroku app of my django project? [closed]
I have developed an web application usig django framework and deployed it on the heroku platform. The code is on my GitHub platform. The problem which I'm facing is that, In my localhost I'm able to see the backgroung img which I have setup but when it's live on the heroku website it's on showing the background image only and rest is fine. Where should I have to do the changes. Is there any other tool where I have to save my media content?? Here is the directory i had set before deploy.Here is the setting file where I have given the root to the media file. This is my base.html My Local Server The actual website. -
Unable to provide windows authentication to Django UI using IIS
i have a django web app installed and hosted on IIS on server . Currently it is not provided with any authentication , but i want to give it windows authentication so that if anyone tries to access the url should provide windows username and password . made a small research on this topic and as am new towards this authentication using windows i want someone's help . So the first step i did was to modify settings.py file of Django project . As seen on question https://stackoverflow.com/questions/26881344/django-authenticate-using-logged-in-windows-domain-user i added MIDDLEWARE_CLASSES = ( ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', ... ) and AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend', ) to settings.py . and next i migrated the app and ran server . restarted the app . and as per the answer for the above stack qustion it required changing or enabling of windows authentication on IIS . did as per the instruction from the answer provided in the above stack question but the issue is no error am getting and no login using windows . it runs as usual without any authentication Is there any other way to do this . Can anyone help me on this stuff -
Django PostgreSQL double index cleanup
We've got this table in our database with 80GB of data and 230GB of Indexes. We are constrained on our disk which is already maxed out. What bothers me is we have two indexes that look pretty darn similar CREATE INDEX tracks_trackpoint_id ON tracks_trackpoint USING btree (id) CREATE UNIQUE INDEX tracks_trackpoint_pkey ON tracks_trackpoint USING btree (id) I have no idea what's the history behind this, but the first one seems quite redundant. What could be the risk of dropping it ? This would buy us one year of storage. -
No buttons are appearing when they are supposed to appear - django template language
So it is supposed to show remove from cart when user has that item in their cart and add to cart when they don't, I am trying to use django template language for this but both buttons are not appearing, home function handles the page i am talking about, It passes all the variables to home.html. home.html <h1>Here are products</h1> <h1>{{ error }}</h1> <h1>Your cart currently costs ${{ price }}</h1> {% for book in books %} <h3>{{ book.name }}</h3> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% for usercart in cart %} {% if book == usercart.book %} <form method="POST" action="/removefromcartforhome/"> {% csrf_token %} <button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button> </form> {% elif book != usercart.book %} <form method="POST" action="/addtocartforhome/"> {% csrf_token %} <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button> </form> {% else %} <form method="POST" action="/addtocartforhome/"> {% csrf_token %} <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button> </form> {% endif %} {% endfor %} {% endfor %} views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from … -
Why does Django Channels AsgiHandler not work with path?
When using Django Channels, in my routing.py, this works: from django.conf.urls import url from channels.http import AsgiHandler from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import my_app.routing application = ProtocolTypeRouter({ 'http': AuthMiddlewareStack( URLRouter ( my_app.routing.http_urlpatterns + [ url("", AsgiHandler) ] ) ) }) But this doesn't: from django.urls import path # <--- Changed from channels.http import AsgiHandler from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import my_app.routing application = ProtocolTypeRouter({ 'http': AuthMiddlewareStack( URLRouter ( my_app.routing.http_urlpatterns + [ path("", AsgiHandler) ] # <--- Changed ) ) }) If it helps, the exception thrown is: 2021-02-05 08:34:25,879 ERROR Exception inside application: No handler for message type http.request File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/middleware.py", line 41, in await inner_instance(receive, send) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/consumer.py", line 62, in __call__ await await_many_dispatch([receive], self.dispatch) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/utils.py", line 52, in await dispatch(result) File "/opt/my_app/venv3/lib64/python3.6/site-packages/asgiref/sync.py", line 244, in __call__ return await asyncio.wait_for(future, timeout=None) File "/usr/lib64/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/usr/lib64/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/db.py", line 14, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "/opt/my_app/venv3/lib64/python3.6/site-packages/asgiref/sync.py", line 277, in thread_handler return func(*args, **kwargs) File "/opt/my_app/venv3/lib64/python3.6/site-packages/channels/consumer.py", line 107, in dispatch raise ValueError("No handler for … -
Use AWS S3 as django storage backend partially
Is there any way to upload some of my DJango media files to AWS S3? Yes, I am aware of the django-storages library but that sets my default storage location to S3. I want to accomplish a hybrid of both S3 and local storage. Is it possible? -
Django request.user will return wrong results when many people use my website at the same time
I'm using Django 3.1, now I'm facing a problem that when many people use my website at the same time, request.user will return wrong results sometimes, but when you clicked next page it will return normal, which is very strange. I guess there'are something wrong in sessions. I have already checked the documents but I don't know what to do :( -
ConnectionResetError: [Errno 54] Connection reset by peer in Django
I am running my django site still on my development folder. I have started getting this error. Which I am not sure what the cause is. The site does load with all the images and styling but I can't get rid of this. I am not sure if this is causing more issues in my site. This is the error in the terminal Settings.py file Debug set to True -
Need help in django project
I have developed a student website using django which includes a database(MySQL), so now I want to run this django project in another system, so how can I run this django project in another system including the database(that is MySQL) -
Got AttributeError when attempting to get a value for field `text` on serializer `CommentSerializer`
I am using Django Rest Framework to make a Blog API. But I have been getting this error when I search for individual comments under each post. The model, serializers and views for Comments is given below: Models.py class Comment(models.Model) : text = models.TextField( validators=[MinLengthValidator(3, "Comment must be greater than 3 characters")] ) post = models.ForeignKey(Post, on_delete=models.CASCADE) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Shows up in the admin list def __str__(self): return (self.post.title) Serializers.py class CommentSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField() post = serializers.StringRelatedField() class Meta: model = Comment fields = ['text', 'created_at', 'post', 'owner'] Views.py class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_object(self, queryset = None, **kwargs): item = self.kwargs.get('pk') return get_list_or_404(Comment, post = item) def get_queryset(self): return Comment.objects.all() Whenever I go to http://localhost:8000/api/comments/1/ this is what happens. Got AttributeError when attempting to get a value for field `text` on serializer `CommentSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `list` instance. Original exception text was: 'list' object has no attribute 'text'. -
Django AWS MySQL
I tried to deploy my application on AWS, but I'm having problems! First, when trying to put MySQL data in settings.py, a problem appears: "Unknown MySQL server host 'myapp.us-east-1.rds.amazonaws.com' I tried with other databases (Postgresql and Oracle) and they worked, but mysql did not. Does anyone know how to solve? I would be grateful. Gratitude. -
how do i fix django Password reset error 200 1903 & 302 0
It gives me the following error and shuts down the program. [05/Feb/2021 19:41:25] "GET / HTTP/1.1" 200 25 [05/Feb/2021 19:41:35] "GET /reset_password/ HTTP/1.1" 200 1903 [05/Feb/2021 19:41:41] "POST /reset_password/ HTTP/1.1" 302 0 My URLS: path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete") and setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '****@gmail.com' EMAIL_HOST_PASSWORD = '********' I have allowed less secure apps on Gmail, but it still gives this error! -
Django query with inner join
With these models: class Categoria(models.Model): titolo=models.CharField(max_length=128, default="unavailable") class Oggetto(models.Model): titolo=models.CharField(max_length=128) desc=models.TextField() url_img=models.URLField() id_categoria=models.ForeignKey(Categoria,on_delete=models.CASCADE,related_name="categoria", default=False) I try this : qs=Oggetto.objects.filter(id=12).select_related().values() to have a SQL : SELECT Oggetto.*,Categoria.titolo FROM Oggetto INNER JOIN Categoria ON (Oggetto.id_categoria=Categoria.id) WHERE Oggetto.id=12 The output (wrong) is : QuerySet [{'id': 12, 'titolo': 'abc', 'desc': 'abc', 'url_img': '', 'id_categoria_id': 1}] -
post to django API returns 403 (Forbidden) when authenticated, but able post when not authenticated
I'm building an app that works as follows: Users fill out data on an html form and submit. the data is posted onto the API (via Fetch). This app uses django, django rest frame work with plain html and vanilla jav My issue is that when the user is authenticated on the API/backend, I cannot post. It returns 403. However, when I am not authenticated I can post data from the form. Here is the JS on the form.html that posts data into the API: <script> console.log('js linked') function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); console.log(csrftoken) function post_report(event) { event.preventDefault(); var contact_email = document.getElementById("contact_email").value var contact_number = document.getElementById("contact_number").value var date_time = document.getElementById("date_time").value var location = document.getElementById("location").value var description = document.getElementById("description").value console.log(contact_email + ' ' + description) fetch("http://127.0.0.1:8000/api/Flight_Safety_Reports/",{ method: "POST", mode: 'same-origin', headers:{ "Accept": "application/json", 'Content-Type':'application/json', 'X-CSRFToken': csrftoken }, …