Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Zappa Django: instead of re-querying the database, it uses an outdated in-memory cache. Can this behavior be changed?
In my project, I use Django as a frontend only. All backend logic is several AWS Lambda Python functions coordinated by the state machine. The database is SQLite in the S3 bucket. I use django_s3_storage and django_s3_sqlite. My backend functions change the number of model instances and their details in the SQLite database. I'd like those changes to be reflected by the Django frontend ASAP. However, it does not happen. I see only the outdated in-memory cache. I have tried several things. My initial view: class AllPortfolioRowsView(ListView): model = PortfolioRow template_name = "portfolio_all_rows.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # do something else context['object_list'] = PortfolioRow.objects.all().order_by('row_type') return context I have read the advice to do stuff inside the get function. In this case, supposedly, a query to the database must be executed every time the function is called. Variant #2: class AllPortfolioRowsView(View): def get(self, request): template = loader.get_template('portfolio_all_rows.html') object_list = PortfolioRow.objects.all().order_by('row_type') # do something else context = { 'object_list': object_list, # other stuff } return HttpResponse(template.render(context, request)) It worked but did not help. Then I tried to force querying the database, as recommended by the Django documentation. Variant #3: class AllPortfolioRowsView(View): def get(self, request): template = loader.get_template('portfolio_all_rows.html') object_list = PortfolioRow.objects.all().order_by('row_type') … -
What is the best way to track users on django website in 2021?
I finished my django project and I would like to add some kind of analytics, custom analytics, Google analytics or something else. I'm looking for best solution and easiest to implement. Can you give me some insights or advice? Thanks in advance! -
Why django respond back "TypeError: argument of type 'NoneType' is not iterable" when I use base64.b64decode
I am in trouble to develop the function to upload user image file into the database. I wrote the code like below from django.core.files.base import ContentFile import base64 def decode_base64_file(file_name, data): if 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: TypeError('invalid_image') return ContentFile(decoded_file, name=file_name) return None Trying to store the user image file temporally and show it in "confirm page". I confirmed that image data captured through browse however when I tried to save it in database, then django respond back that TypeError: argument of type 'NoneType' is not iterable What should I be careful to conduct this code??? best, -
How to set field via function in django model?
I want the field "ripening time" to be determined when the model is created and calculated by function snippet class ActiveBusiness(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None) id = models.AutoField(primary_key=True) business = models.ForeignKey(Business, on_delete=models.CASCADE, default=None) ripeningDate = models.DateTimeField(default=ripeningDate(self)) def __str__(self): return str(self.business.label def ripeningDate(self): ripeningTimeInSeconds = self.business.ripeningTimeInSeconds now = datetime.datetime.now() result = now + datetime.timedelta(seconds = ripeningTimeInSeconds) return result but it is not work if i use @property i dont get it in api what am I doing wrong? -
django is there better variant to use CBV approach in my project?
Sorry for such a long question and my bad english. I have finished Python Crash Course, an introductory programming book by Eric Matthes. After that decided to continue study Django and found that CBV method is more acceptable for site creating. I rewrited via CBV training program from the book which was written by functions, but I still feel a bit lost with methods of CBV after reading the official documentation. Could somebody tell, is there a lot of hardcoding in my CBV variant? And it's possible to do it better ? Every variant works fine. Here the variant of views from the books with comments, I inserted a comments to understand what code does: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import Http404 from .models import Topic, Entry from .forms import TopicForm, EntryForm # Create your views here. def index(request): """Home page of Learning Log.""" return render(request, 'learning_logs/index.html') def more_inf(request): return render(request,'learning_logs/more_inf.html') def topics(request): """List of topics""" public_topics = Topic.objects.filter(public=True).order_by('date_added') if request.user.is_authenticated: private_topics = Topic.objects.filter(owner=request.user).order_by('date_added') topics = public_topics | private_topics else: topics = public_topics context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): """Show one topic with details""" topic = get_object_or_404(Topic, … -
How to create a modal in django without Jquery
Currently, I have created functionality to display some information regarding one of my models in HTML, in the spirit of succinctness, I would like to present the client information model using a modal pop-up window. My main problem is that when the user clicks the view button, I'm getting data from the database and sending it to a view and this is rendered as HTML - I can certainly use Jquery AJAX to pass the data to the server and get a JSON file to construct my form in my main HTML page using bootstrap modal forms, however, is there another more pythonic way to achieve this? views.py #Receives the client name and gets a queryset that is passed on to the HTML page def ind_client_view(request): name = request.GET.get('name','') firstname,lastname = name.split() client = Client.objects.filter(firstname=firstname,lastname=lastname) return render(request,'account/leads_list.html', {'client':client}) {% for lead in pag_leads %} <tr> <td><a href = "{% url 'leads_update' lead.project_id %}">{{ lead.project_id }}</a></td> <td>{{ lead.agent }}</td> <td>{{ lead.company }}</td> <td><a href = "{% url 'ind_client_view' %}?name={{ lead.point_of_contact }}" class="btn btn-primary btn-sm">{{ lead.point_of_contact }}</a></td> <td>{{ lead.country }}</td> <td>{{ lead.services }}</td> <td>{{ lead.expected_licenses }}</td> <td>{{ lead.expected_revenue }}</td> <td>{{ lead.estimated_closing_date }}</td> <td> {% if lead.age_in_days <= 30 %} <b style="color:Red">{{ lead.age_in_days … -
Anotation in Serializer not working correctly
suppose [ {"folder": "cs", "post": {"id": "jqux3ipm", "content": "content", "username": "username", "liked": false, "saved": false, "seen": false}, "liked": true, "saved": true, "seen": false}, ] How do i convert it to [ {"folder": "cs", "post": {"id": "jqux3ipm", "content": "content", "username": "username", "liked": true, "saved": true, "seen": false}, ] models class Post(models.Model): content = ... ... class SavedPost(models.Model): user = models.ForeignKey(User,...) post = models.ForeignKey(Post,...) class LikedPost(models.Model): user = models.ForeignKey(...) post = models.ForeignKey(Post,...) Serializer i am using class SavedPostSerializer(serializers.ModelSerializer): seen = serializers.BooleanField(default=True, read_only=True) liked = serializers.BooleanField(default=False, read_only=True) saved = serializers.BooleanField(default=True, read_only=True) post = PostSerializer(read_only=True) class Meta: model = SavedPost fields = ("folder", "post", "liked", "saved", "seen") view @login_required() def GetSavedPost(request): obj = SavedPost.objects.select_related("post").annotate( liked=Exists(LikedPost.objects.filter( user=request.user, post_id=OuterRef('post_id'))), saved=Exists(SavedPost.objects.filter( user=request.user, post_id=OuterRef('post_id'))) ).filter(user_id=request.user.id) serializer = SavedPostSerializer(obj, many=True) result = JsonResponse(serializer.data, safe=False) return result All i want is to show some anotation field using a defined serializer and extra field i.e. cs. Thanks in advance! -
Django override query set method
I am trying to override get_queryset in a django ViewSet class but I am getting a router error : extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' Here is my ViewSet class : class InvestmentViewSet(NestedViewSetMixin, ModelViewSet): """ A viewset that provides `retrieve`, `create`, and `list` actions for Investments. """ model = Investment serializer_class = InvestmentSerializer queryset = Investment.objects.all() def get_active_investment(self): """Get active investment Only One investment/startup is active """ queryset = Investment.objects.all() active = self.request.query_params.get('active') if active is True: queryset = queryset.filter(investment_status=active) return queryset Here is how I am calling it with router : from django.conf import settings from django.contrib import admin from django.urls import path, re_path from django.views.static import serve from rest_framework_extensions.routers import ExtendedSimpleRouter from back import views router = ExtendedSimpleRouter() ( router.register(r'api/startups', views.StartUpViewSet, basename='startup') .register(r'investments', views.InvestmentViewSet.get_active_investment, basename='startups_investment', parents_query_lookups=['startup']) ) urlpatterns = [ path('admin/', admin.site.urls), *router.urls, re_path(r'media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] -
Hosting Angular and Django on a VPS
I've already hosted my Django application on a VPS using gunicorn and Nginx. I created a config file for the Django app under /etc/nginx/sites-available/myapp and the app is running well on port 80. The below image is the config file regarding the Djagno app: Now, I want to run the Angular application on the same server. How can I do that taking in consideration that I already did a research on it and tried creating a config file for angular under /etc/nginx/sites-available/angular-app but failed? The below image is the config file regarding the Angular app: -
django.db.utils.OperationalError: foreign key mismatch - "businesses_activebusiness" referencing "businesses_business"
I have a Business class, I want to make an active business class that depends on the first class class Business(models.Model): name = models.CharField(max_length=50, primary_key=True,unique=True,default='new') label = models.CharField(max_length=50, blank=True, null=True) ripeningTimeInSeconds = models.IntegerField() requiredLevel = models.IntegerField() price = models.IntegerField() def __str__(self): return str(self.label) class ActiveBusiness(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None) id = models.AutoField(primary_key=True) business = models.ForeignKey(Business, on_delete=models.CASCADE, default=None) def __str__(self): return str(self.business.label) @property def ripeningDate(self): ripeningTimeInSeconds = self.business.ripeningTimeInSeconds now = datetime.datetime.now() result = now + datetime.timedelta(seconds = ripeningTimeInSeconds) return result Why can't I refer to the Business class? Where is the problem here? -
How to declare variable using loop in Python?
I just wanted to know how I can shorten my code using loop in python, can someone help me? Thanks! I'm using Python-flask. app.route('/data', methods=["GET", "POST"]) def data(): con = sqlite3.connect('tmonitor.db') con.row_factory = sqlite3.Row cur = con.cursor() cur.execute("SELECT * FROM monitors ORDER BY id DESC limit 1") rows = cur.fetchall() value = [row[1] for row in rows] //to split the array value1 = '-'.join(str(e) for e in value) value2 = value1.split('-') //Insert inside the loop to shorten the code Cell1_raw = value2[0] Cell2_raw = value2[1] Cell3_raw = value2[2] Cell4_raw = value2[3] Cell5_raw = value2[4] Cell6_raw = value2[5] Cell7_raw = value2[6] Cell8_raw = value2[7] Cell9_raw = value2[8] Cell10_raw = value2[9] // To convert in integer (Also need to shorten the code) Temperature1 = int(Cell1_raw) Temperature2 = int(Cell2_raw) Temperature3 = int(Cell3_raw) Temperature4 = int(Cell4_raw) Temperature5 = int(Cell5_raw) Temperature6 = int(Cell6_raw) Temperature7 = int(Cell7_raw) Temperature8 = int(Cell8_raw) Temperature9 = int(Cell9_raw) Temperature10 = int(Cell10_raw) // to shorten also data = [time() * 1000, Temperature1, Temperature2, Temperature3, Temperature4, Temperature5, Temperature6, Temperature7, Temperature8, Temperature9, Temperature10] response = make_response(json.dumps(data)) response.content_type = 'application/json' return response I added some comments for you to see what needs to be shorten, I'm still studying python, thank you so much! -
How can I get the previous instance of an object in Django templates, dynamically?
So I have a **model** which accumulates most of the other models to display a report. class IpdReport(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) package=models.ForeignKey(Package, on_delete=CASCADE, blank=True, null=True) receivables=models.ForeignKey(Receivables, on_delete=CASCADE, blank=True, null=True) discharge=models.ForeignKey(Discharge, on_delete=CASCADE, blank=True, null=True) realization=models.ForeignKey(Realization, on_delete=CASCADE, blank=True, null=True) lockdata=models.ForeignKey(LockData, on_delete=CASCADE, blank=True, null=True) As you can see, most of the fields are optional. filters.py class IpdFilters(django_filters.FilterSet): patient__name=django_filters.CharFilter(lookup_expr='icontains', label='Name') package__patient_type__patient_type=django_filters.CharFilter(lookup_expr='icontains', label='Type of Patient') realization__amount_received__gt=django_filters.NumberFilter(field_name='realization__amount_received', lookup_expr='gt', label='Min. Amount Received') realization__amount_received__lt=django_filters.NumberFilter(field_name='realization__amount_received', lookup_expr='lt', label='Max. Amount Received') from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from'}), field_name='package__date_of_admission', label='From - Date of Admission ', lookup_expr='gte') to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to'}), field_name='package__date_of_admission', label='To - Date of Admission ', lookup_expr='lte') class Meta: model=IpdReport fields={ 'realization__cash':['exact'] } What I want is, when the context passes an instance to the template, the template should be able to access the previous instance containing the same patient in order for me to use it to display a particular text in one of the table-data based on the condition I put. I tried something like: views.py def ipd_report_view(request): report=IpdReport.objects.all().order_by('id') myFilter=IpdFilters(request.POST, queryset=report) report=myFilter.qs lst=[] temp_lst=[] for indie in report: prev=IpdReport.objects.filter(patient=indie.patient).order_by('id') print('prev ka value: ', prev) for chu in prev: if chu not in lst: lst.append(chu) ln=len(lst) for i in range(0, ln): if i not in temp_lst: temp_lst.append(i) pitch=prev[:ln-1] total1=report.aggregate(Sum('realization__amount_received')) total2=report.aggregate(Sum('realization__deficit_or_surplus_amount')) context={'report': report, 'total1':total1, 'total2':total2, 'myFilter':myFilter, 'previous':lst, 'len':temp_lst, … -
Sign Up view test not passing [Django REST]
I'm trying to test the sign up view in Django using REST Framework but I'm getting an assertio error AssertionError: 201 != 400 when defining self.assertEqual(status.HTTP_201_CREATED, response.status_code). I'm not really sure where this error comes from so I'm asking for some help. Here is what I have: accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomUser(AbstractUser): username = models.CharField(max_length=20, unique=True) email = models.EmailField(_('email address'), unique=True) def __str__(self): return self.email accounts/serializers.py from django.contrib.auth import get_user_model from django.core.validators import EmailValidator from rest_framework import serializers from rest_framework_simplejwt.serializers import TokenObtainPairSerializer import re def company_email_validation(email): pattern = r'(@gmail|@hotmail|@googlemail|@yahoo|@gmx|@ymail|@outlook|@bluewin|@protonmail|@online|@web|@online|@aol|@live)' return bool(re.search(pattern, email)) class UserSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) def validate(self, data): email_validator = EmailValidator() email_validator(data['email']) if (company_email_validation(data['email'])): raise serializers.ValidationError('You must use a company email') if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2') } data['password'] = validated_data['password1'] data['email'] = validated_data['email'] return self.Meta.model.objects.create_user(**data) class Meta: model = get_user_model() fields = ( 'id', 'username', 'email', 'password1', 'password2', ) read_only_fields = ('id',) accounts/views.py from django.contrib.auth import get_user_model from rest_framework import generics from rest_framework_simplejwt.views import TokenObtainPairView from .serializers import UserSerializer, … -
How to create the foreign key relationship between Account and Post models on the model level, not on a database level?
I want to create the foreign key relationship between Account and Post models on the model level, not on a database level. I have created a custom account user, https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#custom-users-and-proxy-models The models are: Account : first_name, last_name, email, password, username Post : user, text, created_at, updated_at class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return self.is_admin # Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY) def has_module_perms(self, app_label): return True class Post(models.Model): user = models.CharField(max_length=30) text = models.TextField(max_length=500) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user -
Django rest framework POST nested serializer using action
I am new to django. I am having trouble with nested serializers. The nested serialization doesn't work as expected. when I am trying to create and post a new student, it does not create and post every thing and I got the following typeError: django.db.models.manager.BaseManager._get_queryset_methods..create_method..manager_method() argument after ** must be a mapping, not str and I see the rest as following: { "is_existing_student": "yes", "name" :"SN school" "street": "Main Road", "city" : "London" "student": {} } But the name of the student should be created too. it should be like this: { "is_existing_student": "yes", "name" :"SN school" "street": "Main Road", "city" : "London" "student": { "first_name": "John" } } Can someone help me? In my serializers.py class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True) class Meta: model = School fields = ['is_existing_student', 'name', 'city', 'street', 'student'] def create(self, validated_data): student_data = validated_data.pop('student') school_instance = School.objects.create(**validated_data) for student_data in student_data: Student.objects.create(school_instance=school_instance, **student_data) return school_instance in my views.py class SchoolViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() @action(detail=True, methods=['POST']) def school(self, request, *args, **kwargs): school_serializer = self.get_serializer(data=request.data) if school_serializer.is_valid(): school_serializer.save() else: return Response(status=status.HTTP_204_NO_CONTENT) -
Why we use JWT if we can use Redux for routes
Sorry for this question, I'm working in a project with React/Django/PostgreSQL, I realised a basic routes managing using Redux. I didn't understand what is the utility of Web Tokens, I want to use them in my project but for now I can see that I can do plenty premission things using Redux states. I really need to know some use cases for using Web Tokens for the whole projects. Thank you -
(421, b'Cannot connect to SMTP server, connect error 10061')
I'm trying to send an actual email to myself from my website using send_mail. I had used localhost and the following cmd command, python -m smtpd -n -c DebuggingServer localhost:1025 in order to test it. It intercepts with no problem, but I don't see anything in my inbox. Here is the settings.py file: EMAIL_HOST = '178.67.220.242' # My current ip address EMAIL_PORT = '587' # Port of the email host EMAIL_HOST_USER = 'b....a1@gmail.com' # Here is my actual email EMAIL_HOST_PASSWORD = '.....' # Here is my actual password from my email login EMAIL_USE_TLS = True EMAIL_USE_SSL = False Here is the views.py file: from django.shortcuts import render from django.core.mail import send_mail from .forms import ContactForm def contact(request): form = ContactForm if request.method == 'POST': message_name = request.POST.get('name') message_email = request.POST.get('email') message = request.POST.get('message') send_mail(message_name, message, message_email, ['b....a1@gmail.com']) return render(request, 'contact.html', {'form': form}) Here is the error: Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\1\PycharmProjects\StasProject\sales_project\contact\views.py", line 15, in contact send_mail(message_name, message, message_email, ['badabuska1@gmail.com']) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\backends\smtp.py", line … -
Django Rest Framework - How can I serialize a complex many-to-many object model with a custom table join?
I'm new to Django and Django REST Framework. I have a fairly complex relationship model, the intent is to have a shopping cart with many orders: class Product(models.Model): name = models.CharField(max_length=200) class Order(models.Model): title = models.CharField(max_length=200) items = models.ManyToManyField(Product, through='TableJoin') class TableJoin(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() I'm having trouble both using the ORM to pull a complete Order model (with relations), and to then serialize that. -
Heroku 500 internal error (due to postgres field errors?)
Im running an app on heroku that has a postgres db. I encountered a strange situation that whenever I pass in more than 50 characters inside the first field (title) of a ModelForm I get an Server Error (500) message and the app crashes. If the length of the input is 50 or less characters then the app works fine. I double checked that in models.py the CharField's max_lenght is more than 50 class Ad(models.Model): title = models.CharField(max_length=240) I also checked that the max character length is 240 in postgres /dt+ table desription Column | Type | Collation | Nullable | Default | Storage | Stats target | Description -----------------------+------------------------+-----------+----------+------------------------------------+----------+--------------+------------- id | integer | | not null | nextval('ads_ad_id_seq'::regclass) | plain | | category | text | | not null | | extended | | title | character varying(240) | | not null | | extended | | I haven't inputed any constraints on character lengths in the forms.py also. And what else is strange that in my local development env (also running on postgres) the app does not crash if I enter more that 50 characters in the title field. Both versions are tracked by git vc. Unfortunately the … -
django Error: Tried everything suggested by every website existing on google but still getting "The given username must be set"
I am working on user registration for an E-commerce Website I am not using any forms.py and there is no Indentation issue. I am passing simple JSON on postman on POST method to check if it is working or not, but I am getting errors. Below is my code and my error. I will be grateful for your help. My model.py from django.db import models from django.contrib.auth.models import AbstractUser import datetime class User(AbstractUser): created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username My View.py class Register(APIView): def post(self, request): username = request.POST.get('username') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') email = request.POST.get('email') if password == confirm_password: if Client.objects.filter(username = username).exists(): return Response({"message": "this username already exist"}) elif Client.objects.filter(email = email).exists(): return Response({"message": "This emaila address is already taken"}) else: user= Client.objects.create_user(username = username, password =confirm_password, email=email) user.save() else: return Response({"message": "Try it again"}, 404) My urls.py from django.urls import path from user_authentication.views import Login, Logout, Register urlpatterns = [ path('login/', Login.as_view()), path('logout/', Logout.as_view()), path('register/', Register.as_view()), ] Error--- Exception Value: The given username must be set Internal Server Error: /register/ Traceback (most recent call last): File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response … -
List liked post in django
Suppose class Post(models.Model): content = models.CharField(...) image = models.ImageField(...) class PostLike(models.Model): user = models.ForiegnKey(User,...) post = models.ForeignKey(Post,...) class PostSave(models.Model): user = models.ForiegnKey(User,...) post = models.ForeignKey(Post,...) How do i list all the liked post in serializers with fields ["content","image","liked","saved"] ? Here liked will be true for all as the list is coming from liked posts. And saved will be true if request.user and post_id in PostSave. view def getLikedPost(request): obj = # Get all the liked post serializer = CustomSerializer(obj.,many=True) result = JsonResponse(serializer.data, safe=False) Help me in completing view and serializer Thanks in Advance! -
Internal Server Error (500) showing on sub-routes when running Django on server
I'm hosting my Django application on a VPS and I'm using Django Rest Framework and the Django Admin Site. Everything seemed working running fine (check the below image), but when I try to click on my API's I'm redirected to a Server Error (500) page. One thing to notice is that when I'm running the app locally on my machine everything is working fine. Below is my settings.py if it can help in anyway: Django settings for thepatron project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_heroku import datetime from dotenv import load_dotenv # Initialize environment variables load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! try: SECRET_KEY = str(os.getenv('SECRET_KEY')) except KeyError as e: raise RuntimeError("Could not find a SECRET_KEY in environment") from e # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ # VPS '194.5.159.80', # … -
Schedule emails on a specific time using Django and celery
This is the use case I am looking for : User will register on my application It is a note making and remainder application While creating remainder users will enter the time my application wants to send user an email at that time I have to use celery for the same I read several posts and stack overflow answers but didn't get proper answer for the same. My application is written in Django. -
Django + ElasticSearch + Docker - Connection Timeout no matter what hostname I use
I'm having issues connecting with my Elasticsearch container since day 1. First I was using elasticsearch as the hostname, then I've tried the container name web_elasticsearch_1, and finally I'd set a Static IP address to the container and passed it in my configuration file. PYPI packages: django==3.2.9 elasticsearch==7.15.1 elasticsearch-dsl==7.4.0 docker-compose.yml version: "3.3" services: web: build: context: . dockerfile: local/Dockerfile image: project32439/python command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" env_file: - local/python.env depends_on: - elasticsearch elasticsearch: image: elasticsearch:7.10.1 environment: - xpack.security.enabled=false - discovery.type=single-node networks: default: ipv4_address: 172.18.0.10 settings.py # Elasticsearch ELASTICSEARCH_HOST = "172.18.0.10" ELASTICSEARCH_PORT = 9200 service.py from django.conf import settings from elasticsearch import Elasticsearch, RequestsHttpConnection es = Elasticsearch( hosts=[{"host": settings.ELASTICSEARCH_HOST, "port": settings.ELASTICSEARCH_PORT}], use_ssl=False, verify_certs=False, connection_class=RequestsHttpConnection, ) traceback HTTPConnectionPool(host='172.18.0.10', port=9200): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x7f1973ebd6d0>, 'Connection to 172.18.0.10 timed out. (connect timeout=5)')) -
Django asgi Single thread executor already being used, would deadlock deployment error
my run command for django asgi application using gunicorn looks like this: gunicorn -b '0.0.0.0:8000' myproject.asgi:application -w 4 -k uvicorn.workers.UvicornWorker --access-logfile /logs/access.log --access-logformat "%(h)s %(l)s %(u)s %(t)s %(r)s %(s)s %(b)s %(f)s" >> /logs/error.log When I try to access any endpoint of the application, I get Single thread executor already being used, would deadlock error. I am using following package versions: Django=3.2.4 asgiref==3.4.0 uvicorn==0.15.0 gunicorn==20.1.0