Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirecting to page with post requet
hey can anyone help me my django website has login page with post as home page then it goes to main content page there is a button to delete my record after delete i want to redirect to the content page but it has a post request of login page so how can i manage it help me out flow chart login(home page)--(Post)--> Content page--> delete function in content page then redirect to content page after deleting item but content has come by post request -
close connection in `StreamingHttpResponse` and do something after that
I use StreamingHttpResponse in django framework. I want to save some records in database after response finished and connection closed. What should I do? class foo(View): def get(self, request): response = StreamingHttpResponse(self._load_stream(request)) return response def _load_stream(self, request): yield('<html><body></body></html>') time.sleep(5000) # close the connection and then save something to database -
how to display serializer in delete action with django rest swagger
By default, django serializer swagger doesn't displayed the Serializer in DELETE method. But, for some reason I need to implement prevent deletion & force deletion case. So, basicly to implement it, we need to add e.g this example inside the request body: { "forceDelete": true } I'm trying to update the serializer inside get_serializer_class function, but it still doesn't work properly. class GroupViewSet(ModelViewSet): permission_classes = (IsOrganizationAdmin,) serializer_class = GroupSerializer search_fields = ('display_name',) def get_serializer_class(self): if self.action == 'destroy': return ForceDeleteSerializer return self.serializer_class -
Clean expected ExclusionConstraint IntegrityError in Django Admin or Form
The docs show a way to embrace the data integrity constraints PostgreSQL provides, f.e. the ExclusionConstraint for overlapping Ranges. You can read the suggested solution from the docs here. I want to have a reservation system which makes sure that a "thing" (here a trainer/teacher) can't be booked twice for a overlapping period of time. I am going with the 2nd example from the documentation where the overlapping criteria is derived from existing fields: from django.contrib.postgres.constraints import ExclusionConstraint from django.contrib.postgres.fields import ( DateTimeRangeField, RangeBoundary, RangeOperators, ) from django.db import models from django.db.models import Func, Q class TsTzRange(Func): function = 'TSTZRANGE' output_field = DateTimeRangeField() class Reservation(models.Model): trainer = models.ForeignKey('Trainer', on_delete=models.CASCADE) start = models.DateTimeField() end = models.DateTimeField() cancelled = models.BooleanField(default=False) class Meta: constraints = [ ExclusionConstraint( name='exclude_overlapping_reservations', expressions=( (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS), ('trainer', RangeOperators.EQUAL), ), condition=Q(cancelled=False), ), ] So, this works just fine for me and when trying to save an invalid Range, I'll get the expected IntegrityError: IntegrityError at /admin/trainer/trainingevent/add/ conflicting key value violates exclusion constraint "exclude_overlapping_reservations" DETAIL: Key (tstzrange(start, "end", '[)'::text), trainer_id)=(["2020-12-19 16:20:00+00","2020-12-19 16:55:00+00"), 1) conflicts with existing key (tstzrange(start, "end", '[)'::text), trainer_id)=(["2020-12-19 16:15:00+00","2020-12-19 16:45:00+00"), 1). Which leads to my question: How can I validate the fields or rather make … -
Django DEPLOYMENT on pythonanywhere - SECRET KEY
I'm trying to deploy my Django Project on pythonanywhere. This is my first time doing anything of the sorts, so I'm pretty confused. On my pc, in the project folder I've created a .env file in which I stored private datas like the SECRET_KEY. Then I created a .gitignore file and inside I wrote .env. So my .gitignore is: .env and my settings.py contains: import os SECRET_KEY = os.getenv("SECRET_KEY") Then I pushed my project on GitHub. Then I cloned it into pythonanywhere. I followed this instruction: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/ so on pythonanywhere I changed the wsgi file. When I write in the console: python3 manage.py migrate I get this error: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I really don't know how to solve this! I've tried several things including saving the private datas on a .bash_profile file, and I tried to store them in a file saved on my Desktop by doing: with open('/.../secret_key.txt') as f: SECRET_KEY = f.read().strip() but on pythonanywhere I get the error: No such file or folder Can someone please help me? Because it's days that I'm trying to solve this! -
best practice django project models
Actualy I am working on a django project and i would like to organize my project as follows : - Backend application (Django) with many applications (client, products,...) - API (Rest Framework) - Frontend (react js). Now my question is about models. what's the best way to organize my models files? Create a template file for all projects as (app with juste models file)? Create a template file by apps like default? or create many models files by applications? Thank you so much -
Get id from path variable url Django
I want my end-point to be like api/units/:id so to pass the id as path variable I have writeen the following code urlpatterns: path('api/units/', UnitDetailsView.as_view()) views.py class UnitDetailsView(APIView): http_method_names = ['get'] permission_classes = (permissions.AllowAny,) serializer_class = UnitDetailsSerializer def get(self, request, id_unit): unit = Unit.objects.get(id=id_unit) return JsonResponse({ 'id': unit.id, }, status=200) However is het a 500 error, because it doesnt recognise the path variable as the id_unit TypeError: get() missing 1 required positional argument: 'id_unit' What is the error and how could i fix it? -
how to display image in django template on browser while showing to user
While trying to display the image on django template from django ckeditor , it shows as follows let me know how to display the image on django template and thanks in advance -
Django model with foreign key throws error on save
I have a model with a foreign key that throws an error when I try to create a new object. I believe that the foreign key field (user_profile_id) is NULL for some reason (it shouldn't be), and when attempting to create, the error is thrown (the field should never be null). This is the error I get: IntegrityError at /api/sensors/ NOT NULL constraint failed: sensors_api_sensor.user_profile_id Request Method: POST Request URL: http://127.0.0.1:8000/api/sensors/ Django Version: 2.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: sensors_api_sensor.user_profile_id Exception Location: /home/vagrant/env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /home/vagrant/env/bin/python3 Python Version: 3.6.9 Python Path: ['/vagrant', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/vagrant/env/lib/python3.6/site-packages'] Server time: Mon, 21 Dec 2020 08:29:01 +0000 models.py: class Sensor(models.Model): """Database model for users' sensors""" user_profile = models.ForeignKey( settings.AUTH_USER_MODEL, # first argument is the remote model for this foreign key on_delete=models.CASCADE # if ForeignKey is deleted, delete all associations ) name = models.CharField(max_length=255) sensor_type = models.CharField(max_length=255) surrounding = models.CharField(max_length=255) latitude = models.FloatField() longitude = models.FloatField() created_at = models.DateTimeField(auto_now_add=True, null=False) # auto adds creation timestamp UTC for each object updated_at = models.DateTimeField(auto_now=True, null=False) # other fields required REQUIRED_FIELDS = ['user_profile','name','type','surrounding'] # model to string conversion method def __str__(self): """Return the model as a string""" return self.name … -
Django REST framework custom model permissions
I try to create django custom permission for a model based on user roles. Organization Model: class Organization_Model(models.Model): id = models.AutoField(primary_key=True, unique=False, editable=False) Name = models.CharField() Organization Roles: class Organization_Roles_Model(models.Model): id = models.AutoField(primary_key=True, unique=False, editable=False) Name = models.CharField() Organization Members: class Organization_Members_Model(models.Model): id = models.AutoField(primary_key=True, unique=False, editable=False) Organization = models.ForeignKey(Organization_Model) User = models.ForeignKey(User) Role = models.ForeignKey(Organization_Roles_Model) Organization Groups: class Organization_AssetsGroups_Model(models.Model): id = models.AutoField(primary_key=True, unique=False, editable=False) Organization = models.ForeignKey(Organization_Model) Name = models.CharField() Custom Permissions: class isOrgOwnerOrAdmin(BasePermission): def has_object_permission(self, request, view, object): User = request.user Roles = Organization_Roles_Model.objects.filter(Name__in=['Owner', 'Admin']) OrgsMember = [OrgID for OrgID in Organization_Members_Model.objects.filter(User=User, Role__in=Roles).values_list('Organization', flat=True)] if object.id in OrgsMember: return True I've created this permission that can be applied only for Organization_Model, but I want to create a permission that can be applied to all objects that are linked to Organization_Model based on their roles in the organization. How can I achieve this easily without creating a permissions for each object that is related to Organization_Model? -
TypeError at /admin/location __str__ returned non-string (type NoneType)
I have a piece of code and each time I want to render the frontend template, it gives just 'None' at every segment such as name, phone etc. When I want to see it from admin page, it throws an error: TypeError at /admin/accounts/student/2/change/ str__ returned non-string (type NoneType) I'm completely new to Django. If anyone could help me, I'll be very grateful. Thanks in advance. Here is my models.py: from django.contrib.auth.models import User # Create your models here. class Student(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(null= True, blank= True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Books(models.Model): CATEGORY = ( ('Physics', 'Physics'), ('Chemistry', 'Chemistry'), ('Mathematics', 'Mathematics'), ) name = models.CharField(max_length=200, null=True) author = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Issue(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) student = models.ForeignKey(Student, null=True, on_delete= models.SET_NULL) book = models.ForeignKey(Books, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, … -
Is it possible to use the same database for two Django projects containing different models?
We planned for two Django projects. Say, Project-1 contains Model A and B. and Other Project-2 contains Model C and D. But I am afraid if it possible or not as I am new in the Django World. Your suggestions would be highly appreciated. -
<int: category> shows up as string in url
I was doing endpoint and using two pk in url. But when using <int: category> it still displays as a string path('<int:pk>/categories/<int:category>/', views.Category.as_view({'put': 'update'})) How do I change string to int? -
Deploy Django project on Hostinger VPS [closed]
I have purchased Hostinger VPS plan. I have a django project ready and running on my local host server. How do I setup the environment and run my project online. Any links or tutorials that would guide me step by step are also appreciated. -
How to split django log?
txt = "[28/Oct/2020 00:07:59] INFO [django.vino.f1:597] Watching for file changes with StatReloader\n [28/Oct/2020 00:08:04] INFO [django.vino:154] "GET / HTTP/1.1" 200 30128" want to split above log . any way to [28/Oct/2020 00:07:59] based on this pattern split (using re ) expected output : ["[28/Oct/2020 00:07:59] INFO [django.vino.f1:597] Watching for file changes with StatReloader", "[28/Oct/2020 00:08:04] INFO [django.vino:154] "GET / HTTP/1.1" 200 30128"] -
Creating columns inside column in MongoDB using models in django
Currently i am working with latest versions Python 3 and Django 3. I want to create columns inside column in MongoDB using models in Django. Ex: column name: Emp_name inside Emp_name there should be a first_name and last_name columns. Can anyone please help over here ASAP -
Unable to render a Django view function from React js forms
We usually use Jinja tags to submit forms through Django Templates i.e {% url 'view_name' %} but this does not work in React.This gaves syntax error and hence i tried as below. But this too does'nt work. React Js Code - <form onSubmit = 'form_submit' method = "post"> <DjangoCSRFToken/> <input type = "text" placeholder = "Email" name = "email"></input><br/> <input type = "password" placeholder = "Password" name = "password"></input><br/> <input type = "password" placeholder = "Confirm Password" name = "password1"></input> <input type = "submit"></input> </form> -
In Django REST Framework, Using ModelViewSet with renderers,
I'm using ModelViewSet and struggling to setup a rendering standard. The documentation doesn't show how to use ModelViewSet with drf renderers. I want the output to be of this format: Format : {'message': <custom message>, 'data': <output from ModelViewSet>} Code: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() permission_classes = [permissions.IsAuthenticated] renderer_classes = [GenericAPIRenderer] # How to Override? class GenericAPIRenderer(renderers.JSONRenderer): charset = 'utf-8' def render(self, data, media_type=None, renderer_context=None): pass -
how to make django crispy forms responsive?
I understand that the Djago crispy forms makes the forms look good, but how can we make the forms responsive? {% load crispy_forms_tags %} <form method="POST" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn-purple fa-pull-right">Sign-In</button> <br> </form> -
AWS Elastic Beanstalk [error] 2540#0: *1 connect() failed (111: Connection refused) while connecting to upstream
I'm getting this error when trying to use AWS Elastic Beanstalk to connect to my Django code: [error] 2540#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.23.63, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" My log is displayed below: ---------------------------------------- /var/log/nginx/error.log ---------------------------------------- 2020/12/21 03:43:19 [error] 2540#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.23.63, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:22 [error] 2540#0: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.160, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:34 [error] 2540#0: *5 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.23.63, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:37 [error] 2540#0: *7 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.160, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:49 [error] 2540#0: *9 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.23.63, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:52 [error] 2540#0: *11 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.160, server: , request: "GET / … -
how to remove html tags in django template on browser while showing to user
As shown in figure i used {{options|safe}} for rendering options in my django 3.0 polls application even though it is rendering like that and i don't know how to remove the tags from rendered string, thanks for help in advance regarding tag error -
How to change django filter_horizontal filter parammeter
I want to add product to category model in admin page. models.py class Product(models.Model): name = models.CharField(max_length=20) image = models.ImageField(upload_to='product/') def __str__(self): return self.name class Categorymodels.Model): category_name = models.CharField(max_length=20) category_product = models.ManyToManyField(Product, blank=True, related_name='category_product') def __str__(self): return self.promo_name admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): filter_horizontal = ('category_product', ) pass When adding products to category, I can use filtering but it filters only by product name. How do I filter something else. -
What error to raise with wrong post request body?
I am new to Django and have an endpoint that accepts post requests. The endpoint expects a specific set of keys in the post request body. What type of Exception should I raise if they don't provide the right keys? ValueError? Thanks! -
get context data in get_queryset
I have BaseContext and Listview which is for Searching in multiple models, Search Class inherits from BaseContext. I set the current user to context and want to use it in my def get_queryset method, But it doesn't work. I think in Search CBV get_context_data execute after get_queryset that's why, self.user is None. class BaseContext(ContextMixin): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) request = self.request if request.COOKIES.get('token') is not None: ... user = Users.objects.filter(user_id=user_id).first() context.update({'current_user': user}) context.update({'is_logged_in ': True}) else: context.update({'is_logged_in ': False}) return context class Search(BaseContext, ListView): template_name = 'search.html' context_object_name = "results" paginate_by = 15 user = None def get_queryset(self): query = self.request.GET.get('search', None) if query is not None and self.user is not None: ... return queryset_chain return faqModel.objects.none() def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if 'is_logged_in' in context and context['is_logged_in']: self.user = context['current_user'] else: redirect("index") return context My question is how can I get context data in def get_queryset(self)? -
ttributeError: type object '' has no attribute 'get_extra_actions'
I am new to Django , and totally confused about the error I face. i am trying to create a rest api and apply django filtering option to it. here is my view code. @permission_classes([AllowAny]) class op_listView(generics.ListAPIView): serializer_class = op_Serializer queryset = Op.objects.all() filter_backends = (DjangoFilterBackend,OrderingFilter, SearchFilter) filter_fields=('website', 'organization__name', 'sectors__name','countries__name') my model class Op(models.Model): website = models.CharField(max_length=40) op_link = models.CharField(null=True, max_length=200) title = models.TextField(null=True) description = models.TextField(null=True) organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) close_date = models.DateField(null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) checksum = models.CharField(max_length=200, null=True) relevancy = models.IntegerField(null=True) mark_relevant = models.IntegerField(null=True) published_date = models.DateField(null=True) language = models.ForeignKey(Language, on_delete=models.DO_NOTHING, default=105) status = models.IntegerField(null=True, default=0) read_status = models.IntegerField(default=0) @property def attachments(self): return self.attachments_set.all() @property def countries(self): return self.country_set.all() @property def sectors(self): return self.sector_set.all() class Meta: db_table = "op" my serializer class op_Serializer(serializers.ModelSerializer) : attachments = attachments_Serializer(many=True , required=False) countries = country_Serializer(many=True , required=False) sectors = sector_Serializer(many=True , required=False) class Meta : model = Op fields = ['id', 'website', 'op_link', 'title', 'description' , 'organization' , 'close_date' , 'created_at', 'relevancy', 'published_date', 'language' , 'status' , 'read_status' , 'attachments', 'countries', 'sectors'] depth = 2 urls from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('op-filter', views.op_listView, basename='op-filter') urlpatterns = router.urls my code does not work and …