Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to combine list and retrieve API views in Django rest framework
I am new to DRF, and was thinking of providing List and Retrieve functionality from a single view. I figured out generic views are the shortest and easiest to handle with, but there isn't any views that allow only list and retrieve functionalities. There is a ListCreateAPIView but I dont want any post data. I guess i can use a mixin, but don't know how. Maybe like this?: class PostView(generics.ListAPIView, mixins.RetrieveModelMixin): queryset = Post.objects.all() serializer_class =myserializer is that the right way? -
how to prevent user to update a post after 24 hours django
i want to prevent the user to update the post after 24 hours from the post date class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title= models.CharField(max_length=50) post = models.TextField(max_length=400) date = models.DateTimeField(auto_now_add=True) edit = models.DateTimeField(auto_now=True) class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView): model = Post form_class = PostForm success_message = "updated successfully" template_name = 'store/create.html' success_url = reverse_lazy('lists') def form_valid(self,form): return super().form_valid(form) i want to let the user only be able to update the post before 24 hours during the Post date thanks -
How to filter the category in Django properly?
I have categories named 'person' in my Django Blog. In my blog, Each post(article) has 1 ~ multiple categories and when I click 1 of those categories, it will show all the posts under that category. However, for some categories especially which has only English Alphabet like 'Steve', shows the same post multiple times. I think using objects.filter has some problem with filtering it but am not sure what exactly the problem is. Do you have any solution for this issue? the below are my codes. models.py class Category(models.Model): person = models.CharField(max_length=20) description = models.TextField() slug = models.SlugField() def __str__(self): return self.person views.py def blog_category(request, category): posts = Post.objects.filter(categories__person__contains=category).order_by( "-created_on" ) context = {"category": category, "posts": posts} return render(request, "blog_category.html", context) -
local variable 'context' referenced before assignment in django
from django.shortcuts import render from main import (models,forms) from django.http import HttpResponseRedirect Create your views here. def index(request): return render (request, 'index.txt') def about(request): return render (request, 'about.txt') def contact(request): contactform = forms.ContactForm() if request.method == "POST": contactform = forms.ContactForm(request.POST) if contactform.is_valid(): contact = contactform.save() return HttpResponseRedirect('/contact') context = { "contactform" : contactform } return render(request, 'contact.txt', context) def post(request): return render (request, 'post.txt') -
Can Django-apps be treated and used as Microservices?
I theoretically know the concept of microservices and know and use the Django-apps. So, Django-apps are there for SOC(separation of concerns) by modularization. And the microservice idea is to bring scalability by breaking whole system into a number of independent systems. So, my confusion and question are Can we treat and make Django-apps as microservices? Or separate projects must be created for that, so as to handle the difference in database and server-deployment?. I hope I have made my question clear. Thanks -
Django Channels Routing with Mulitiple ProtocolTypeRouter
I have 2 different django routings, where one is used along withAuthMiddlewareStack and the other would work with unauthenticated. How do I define both the conditions for auth and unauth consumer URLs: something like this : from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import OriginValidator import chat.routing import dsock.routing application = ProtocolTypeRouter({ 'websocket': OriginValidator( AuthMiddlewareStack( URLRouter( auth.routing.websocket_urlpatterns ) ), ['http://127.0.0.1:8080','localhost','127.0.0.1','dflaws.io'], #https://channels.readthedocs.io/en/latest/topics/security.html ), 'websocket-unauth': URLRouter( un_auth.routing.websocket_urlpatterns ) }) -
Django App Not Working After Deployment to heroku
The App is A Blog Post App That is Working fine Locally But After I Deployed It To Heroku, The App Cannot run. I did more Than a week trying to fix it through the views and models with no success. This Is The Error When Trying To Open The App This My Views.py This The Models.py 1/2 The Models.py 2/2 -
from.is_valid() returns false
I want to save customer entry in my database. I have created a model form and trying to save it. but its not working. Where is the problem for this ? my models.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name my forms.py class CustomerEntryForm(ModelForm): class Meta: model = Customer fields = ['name', 'phone', 'email'] my views.py def customer_entry(request): if request.method == 'POST': form = CustomerEntryForm(request.POST) print(form.is_valid()) context = {'form': form} return render(request, 'accounts/entry.html', context) my urls.py urlpatterns = [ path('', views.customer_entry, name="entry"), path('register/', views.registerPage, name="register"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('home/', views.home, name="home"), ] my template <form method="POST" action="{% url 'entry' %}"> {% csrf_token %} <label for="">Name</label><br> <div class="input-group mb-3"> <input type="text" name="name" class="form-control"> </div> <label for="">Phone</label><br> <div class="input-group mb-2"> <input type="text" name="phone" class="form-control" > </div> <label for="">Email</label><br> <div class="input-group mb-2"> <input type="text" name="phone" class="form-control" > </div> <input class="btn login_btn" type="submit" value="save"> </form> -
how to get the values from manytomanyfield of another model in django
There are two models:Client and Event that is used.So Is there any way like i can access and save values in client_members that take only those values that are selected in Client objects. class Client(models.Model): company_name = models.CharField(_("Company name"), max_length=255) members = models.ManyToManyField(to=User,limit_choices_to={"is_staff":True}, blank=True) class Event(models.Model): title = models.CharField(_("Title"), max_length=255) client_members = models.ManyToManyField(to=User, limit_choices_to={"is_staff":False, "is_superuser":False}, related_name='%(class)s_clientmembers') -
Python 'different_locale' bad locale conversion
conditions = [] for i in range(1, 13): with different_locale('lt_LT'): conditions.append(calendar.month_name[i]) Trying to get all months in my native "Lithuanian" language. Result of the code : ['sausis', 'vasaris', 'kovas', 'balandis', 'geguþë', 'birþelis', 'liepa', 'rugpjûtis', 'rugsëjis', 'spalis', 'lapkritis', 'gruodis'] expected result: ['sausis', 'vasaris', 'kovas', 'balandis', 'gegužė', 'birželis', 'liepa', 'rugpjūtis', 'rugsėjis', 'spalis', 'lapkritis', 'gruodis'] Also tried "lt_LT.UTF-8" but got these results : 'gegužÄ\x97', 'birželis' Any ideas why? -
Object of type timedelta is not JSON serializable while using django-celery-beat
This is my first attempt with the celery so there might be some issues. Here I want to create Task Object every 1 minutes in the database so I used django-celery-beat. I want to use custom scheduler class later so for this purpose I used the django-celery-beat package. But I am not getting the results. I used the django form to create the TaskModel object and write a task in tasks.py to run the view every 1 minutes. But it throws this error Exception Type: EncodeError Exception Value: Object of type timedelta is not JSON serializable I started celery in one console with the command $ celery -A proj beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler and started django server in another console with command py manage.py runserver settings.py CELERY_BROKER_URL = 'amqp://localhost' CELERY_BEAT_SCHEDULE = { 'task-first': { 'task': 'scheduler.tasks.create_task', 'schedule': timedelta(minutes=1) }, celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_demo.settings') app = Celery('celery_demo') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # … -
'NoneType' object is not iterable - issue with context in Django
I have this models.py: class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return "%s" % (self.start_date_time) This is my context_processors.py: def events(request): return { 'next_events': dateEvent.objects.all(), } which is registered in my settings.py: 'OPTIONS': { 'context_processors': [ 'nms_app.context_processors.events' I'm getting TypeError at / 'NoneType' object is not iterable Exception Location: /home/luca/python_ve/lib/python3.8/site-packages/django/template/context.py in bind_template, line 246 /usr/local/lib/python3.8/contextlib.py in __enter__ return next(self.gen) … ▼ Local vars Variable Value self <contextlib._GeneratorContextManager object at 0x7fe90a3e7a90> when visiting any page of my website, and I can't understand why. Can someone help me finding the culprit? I can't see why dateEvent is NoneType; it is populated with valid data. -
Django Models with both same and unique fields
I am working on an inventory management system and am looking to see if I can simplify and reduce the amount of hard coding. This is completely a conceptional question. Say I have two products: Clothing Shoes They share mostly the same fields: Style-ID Brand Name Size They also have some unique fields: Clothing Clothing Category Shoes Shoe Width And some fields which they share, but would have different choices: Age ("Adult", "Children", "Infant" for clothing. "Adult", "GS", "PS", "TS" for shoes) Currently I have two models: "ShoeProduct" and "ClothingProduct", but this seems redundant as they could conceivably share the same datatable and are certainly going to be used in the same functions and manipulated in the same ways. Is there a more efficient way of going about this? (My first thought is one Product model and then field kwargs for the unique fields, but I can't figure out if this is possible in django.) And to clarify, the base case vanilla use for these models is the user would enter data into an html form and once submitted would save this model to the database. Then, as purchase and sales data are fed to the server via various api's, … -
Problem with rq background jobs in Django Heroku
I have Django app which makes lots of different analysis Here is the structure of the view: def analysis(request): making analysis 1 ... making analysis 2 ... making analysis 3 ... ........ making analysis 50 ... return render(request, 'checkapp/shots.html', var) The problem is that all these analysis takes about 1-2 minutes. While development I tested my app locally and it is working fine there. But when I deployed it on Heroku, it turned out, that heroku has 30 sec timeout limit. I was told to use background jobs. I used python RQ. Now the code is def analysis(request): task_1 = q.enqueue(function-1) time.sleep(2) task_1_res = task_fb.result task_2 = q.enqueue(function-2) time.sleep(2) task_2_res = task_3.result task_3 = q.enqueue(function-3) time.sleep(2) task_3_res = task_3.result ..... task_50 = q.enqueue(function-50) time.sleep(2) task_50_res = task_50.result return render(request, 'checkapp/shots.html', var) But I still have the same problem. I have Request timeout error... -
Django duplicates objects after reverse ordering
I'm running into a problem with requests in Django. I have a simple model with several fields include DateTimeField 'event_date'. In a view.py I make a request and return objects from this model: return Event.objects.filter(publish_date__lte=currentTime).order_by('-event_date') And sometimes (I can't see a system) response looks like this: Object5 Object1 Object3 Object2 Object1 (for the second time and where is Object4?) Interesting, if I change ordering to .order_by('event_date') - straight, not reverse, everything is ok: Object1 Object2 Object3 Object4 Object5 What is it? Could this be due to the fact that several objects have the same value of 'event_date' field? -
Show different examples for request body on Swagger with Django
I'm trying to show different examples for different content types in Swagger. I have the following method decorator for the corresponding view: from drf_yasg.utils import swagger_auto_schema from django.utils.decorators import method_decorator from drf_yasg import openapi test_decorator = method_decorator(name='post', decorator=swagger_auto_schema( tags=['Models'], responses={ "200": ModelListSerializer, "400": "Validation Error", "403": "Permission Error", "404": "Not Found Error", }, consumes={'text/plain', 'application/json'} )) I want to be able to receive both 'text/plain' and 'application/json' types and I want to show different examples for each of them. When I added the consumes field, I was able to get a dropdown list for Parameter content type. As far as I understood, it is not possible to give a list or a dictionary for the request_body field. I've seen here in Request and Response Body Examples that in content field, you can define examples. I have tried passing the following to the request_body field: request_body=Schema( type=openapi.TYPE_STRING, example='Test string', content='text/plain' ) request_body=Schema( type=openapi.TYPE_OBJECT, properties={ 'field_1': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'field_2': openapi.Schema(type=openapi.TYPE_STRING, description='string'), }, example={ 'field_1': 'field_1_value', 'field_2': 'field_2_value' }, content='application/json' ) Is there a way to combine them? I'm using: Django==3.0.2 drf_yasg==1.17.0 django-rest-swagger==2.2.0 -
Internal Server Error 500 Django, Value error:/
its leading to internal server error 500 settings.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ 'static' ] Internal Server Error: / ValueError at / Missing staticfiles manifest entry for 'images\favicon.ico' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.4 Python Executable: D:\Amtpl project by aman\AMTPL - Copy\env\Scripts\python.exe Python Version: 3.8.0 -
Could not joint two tables with django rest framework
I am trying to join two tables and serialize them as an API. I referred to the docs of the Django rest framework and tried a code. It didn't work. Could not resolve the problem even after may try. I am trying to get a JSON file like { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement'}, {'order': 2, 'title': 'What More Can I Say'}, {'order': 3, 'title': 'Encore'}, ... ], } But what I get is { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', } This is the model file I am using Model File from django.db import models from django.contrib.auth.models import User STATUS_CHOICE = ( ('simple', 'simple'), ('intermediate', 'intermediate'), ) class Quiz(models.Model): quiz_name = models.CharField(max_length=1000) video_id = models.ForeignKey("youtube.Youtube", on_delete=models.CASCADE) questions_count = models.IntegerField(default=0) description = models.CharField(max_length=70, null=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField() pass_mark = models.IntegerField() class Meta: ordering = ['created'] def __str__(self): return self.quiz_name class Category(models.Model): category = models.CharField(max_length=20, choices=STATUS_CHOICE, default='simple') quiz_id = models.ForeignKey(Quiz, on_delete=models.CASCADE) def __str__(self): return self.category class Questions(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.CharField(max_length=1000) mark = models.IntegerField() def __str__(self): return self.question class Choice(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) choice_1 = models.CharField(max_length=1000) choice_2 = models.CharField(max_length=1000) choice_3 = models.CharField(max_length=1000) choice_4 … -
How to deactivate users using django-allauth?
I am using django cookie cutter and have implemented a way to delete users. I want a second thought on whether it is the correct way to delete users or not. Views.py class UserDeleteView(LoginRequiredMixin, TemplateView): template_name = 'users/user_delete.html' user_delete_view = UserDeleteView.as_view() user_delete.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}{{ user.username }}{% endblock %} {% block content %} <h1>{{ user.username }}</h1> <form class="form-horizontal" method="post" action="{% url 'users:update' %}"> {% csrf_token %} {{ form|crispy }} <div class="control-group"> <div class="controls"> <p>Press delete to delete your profile</p> <button type="submit" class="btn btn-primary">Delete</button> </div> </div> </form> {% endblock %} urls.py from django.urls import path from alife.users.views import ( user_redirect_view, user_update_view, user_detail_view, user_delete_view, ) app_name = "users" urlpatterns = [ path("~redirect/", view=user_redirect_view, name="redirect"), path("~update/", view=user_update_view, name="update"), path("<slug:pk>/", view=user_detail_view, name="detail"), path("delete/<slug:pk>/", view=user_delete_view, name="delete"), ] -
How to add a search bar functionality to all the templates of django?
I am trying to add a search bar in my django site. I added a form in my base template. I have added the functionality to my home view. It is working in the home view. But not in other views. I tried creating a new view but i.e. Is not working too. Please tell me what should I do? -
django filter if object appears in another table
I have a model Device and a model BrokenSensor. In the BrokenSensor table, all the devices with broken sensor get a row. The BrokenSensor model looks like this: class BrokenSensor(models.Model): sensor = models.PositiveIntegerField(choices=Sensor.choices()) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="brokensensor" ) def __str__(self): # pragma: no cover return "pk{} - device: {} - sensor: {}".format( self.pk, self.device_id, self.sensor ) How can I do the most efficient way this query: Give me all the devices, except the devices the BrokenSensor table -
how can I get some latest objects from DB without reading all of the objects in Django?
There's some functions in Django to help you get first or last record, such as first(), earliest(), last() and latest(). What I'm looking for is a function to get some latest objects without reading all of data. For example something like this to get latest 3 object: latest_three_objects = my_model.objects.get_latest(count=3) PS: I know that I can get it in this way: latest_three_objects = my_model.objects.all()[:3] But I think it will read all of my_model data from DB and it's not efficient! Any thoughts? -
What backend framework to use for a full stack developer, Node.js (express) or Django?
I learned django for full MPA websites using HTML, CSS and JavaScript initially. Then I wanted to learn React for creating SPAs and so I learned JS again in depth and learned React with Django. Django, even though is batteries included, I started finding it very confusing. Also the there isn’t much content on the internet to learn how django actually works. So I am thinking of learning express JS for backend because I have heard that it is intuitive and well explanatory. Also it has good courses (including MERN stack courses). Just wanted to take advice from someone experienced if this could be a wrong call? Should I stick to Django and learn more about it in depth or should I switch to Express JS. I just want to learn one to be a successfull Full Stack Web Developer. PS: I am equally good at JS and Python. -
In django how to submit form using JS and XMLHttpRequest and then how to retreive those datas in views.py
I am facing error which is: Forbidden (CSRF token missing or incorrect.): /formsubmit [02/Jun/2020 17:38:04] "POST /formsubmit HTTP/1.1" 403 2513 [02/Jun/2020 17:38:05] "GET /?csrfmiddlewaretoken=GiH9HRWEdUnVdvYEGj2vVSvM1A7cStTUGNZ5WjLUcQdqzOl6kyJ8H84qy2sY5D7p&name=arnab HTTP/1.1" 200 647 Its telling csrf token is missing but again csrf token is showing.Please Help Me. My entire code is as follows: my html: <form enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="name"> <button onclick="btnclick()"> CLICK </button> my script: <script> function btnclick() { alert("alert printing") var name=document.getElementsByName('name'); var formdata=new FormData(); formdata.append("name",name); alert("form data appended"); xhr=new XMLHttpRequest(); xhr.open("POST","formsubmit",true); xhr.send(formdata); alert("formdata sent"); } my urls.py: urlpatterns = [ path('',views.uploadpage,name="uploadpage"), path('upload',views.upload,name="upload"), path('formsubmit',views.formsubmit,name="formsubmit"), ] my views.py: def formsubmit(request): name=request.POST.get('name') print(">>>>>>>>>>>>>>>>>>>>>>",name) return HttpResponse("I AM OUT !!!!!!!!!!!!") -
How to to implement user profile picture with python social auth using Django on Google App Engine via Google Cloud Storage
I have successfully been using social auth for using Google And Facebook signin. How can I get the user image for each user, both new ones and that have already registered in the past ? MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'mysite.signup.views.EmailBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'posts.views.update_user_social_data' )