Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FAILED TO SAVE DJANGO INLINE FORMSET WITH HTML INPUT TO DB
I tried to return data from Purchase Order Model to Grn Form and i want to save it in Grn Model but i cant save it. Here is my view class and grn form which return data but cant save to db class view.py class CreateGrn(LoginRequiredMixin, CreateView): model= GrnModel template_name = "inventory/grn_create.html" class GrnCreate(LoginRequiredMixin, CreateView): model = GrnModel template_name = "inventory/grn_create.html" form_class = GrnForm success_url = reverse_lazy("/") def get_context_data(self, **kwargs): data = super(GrnCreate, self).get_context_data(**kwargs) if self.request.POST: data['formset'] = Grn_LineItemFormset(self.request.POST) else: data['formset'] = Grn_LineItemFormset() data['grn_no'] = GrnModel.objects.filter(company_grn = self.request.user.first_name).order_by('-id')[:1] pk = self.kwargs["pk"] data['form_lpo'] = PurchaseOrderModel.objects.get(pk = pk) #data['lpo_line_item'] = data['form_lpo'].purchaseorder_lineitem_set.all() return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): form.instance.grn_user = self.request.user self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(GrnCreate, self).form_valid(form) html template <div class="container1" style="width: 125%;"> <form class="/purchase_order_list" method="POST" action="">{% csrf_token %} <div class="column is-one-third" style="line-height: 10px;"> <div class="field" style="margin-left: 85.7%; width: 150px; margin-top: 6%;"><br> <label>Lpo No.</label> <div class="control"> <input class="input form-control" value="{{ form_lpo.lpo_number }}"> </div> </div> </div> <div class="column is-one-third"> <div class="field" style="margin-left: 85.7%; width: 150px; margin-top: 0.2%;"> <label>Grn No.</label> <div class="control"> <input class="input form-control" value="{{ form_lpo.grn_number }}"> </div> </div> </div> </div> </div> <div class="columns is-centered"> <div class="column is-one-third"> <div class="col-md-4 mb-3"> … -
Requesting id in post request returns none
I am trying to build a social media like app in Django using mongo db where users can log in and follow/unfollow each other. Here is the code for models.py from django.db import models import uuid from datetime import datetime from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model # Create your models here. class User(AbstractUser): username = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) class FollowersCount(models.Model): follower = models.CharField(max_length=100) user = models.CharField(max_length=100) Here is the code for views.py # sign in class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'jwt': token } return response # logged in user follows / unfollows user based on id class FollowView(APIView): def post(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') follower = User.objects.filter(id=payload['id']).first() print(follower) if request.method == 'POST': user = request.POST.get('id') user_followed = user print(user_followed) response = Response() if FollowersCount.objects.filter(follower=follower, user=user_followed).first(): delete_follower = FollowersCount.objects.get(follower=follower, … -
Django deployment and virtual environment
I am aware that there are many questions regarding Django and virtual environments, but I cannot wrap my head around the use of virtual environments with respect to deploying my Django app (locally) via uwsgi/nginx. My setup includes a virtual environment (with Django and uwsgi), my Django app, nginx and PostgreSQL. The app was created before the virtual environment, and I applied only a single change to manage.py: #!/Users/snafu/virtualdjango/bin/python3 When I start up the uwsgi located in the virtual environment (with the appropriate .ini file), everything works right away, but I wonder why. I did not need to fiddle around with the $PYTHONPATH, or append the site packages directory to the system path in manage.py, or activate the virtual environment at any point (apart from the initial installation of packages), although the boilerplate comment in manage.py explicitly mentions an inactive virtual environment as a possible reason for an import error. -
Custom User model or User Profile model with one to one relationship to the user model
I am a newbie to web developmnet. I'm using django and lately I have been realy confused and undecided on wether I should use a Custom user model with additional fields I need or create a seperate User profile model with one to one relationship with the user model. What is the best practice?. In which ever case is best I would like to aslo add the fields like 'followers', 'following', 'likes', 'connections' and users should be able to easily edit some details on their accounts after creating, which method is the best? -
Reverse for 'car_details' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['cars(?P<id>[0-9]+)/car_details\\Z']
In urls.py urlpatterns = [ path('', views.cars, name='cars'), path('int:id/car_details', views.car_details, name='car_details'), ] In views.py def car_details(request, id): single_car = get_object_or_404(Car, pk=id), id = 1 data = { 'single_car': single_car, # 'url': url, } reverse('single_car', args=(id)) return render(request, 'cars/car_details.html', data) In templates { %for car in cars %} {{car.car_title}} {{car.state}}, {{car.city}} endfor %} I also tried with reverse function it doesnot works get an same error tried with reverse function in views.py it doesnot works get an same error -
form don't save in django
I create a weblog and want add create view this is my form def create_blog_view(request): if request.method == 'POST': blog_form = BlogForm(request.POST) if blog_form.is_valid(): new_form = blog_form.save(commit=False) new_form.author = request.user new_form.save() return redirect('blog_list') else: print('its bog') else: blog_form = BlogForm() return render(request, 'pages/create_blog.html', context={ 'form': blog_form }) and this my model class Blog(models.Model): title = models.CharField(max_length=100) cover = models.ImageField(upload_to='blog_cover/') description = models.CharField(max_length=200) text = models.TextField() author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) active = models.BooleanField(default=False) date_create = models.DateField(auto_now_add=True) date_modified = models.DateField(auto_now=True) def __str__(self): return f'{self.title} : {self.author}' def get_absolute_url(self): return reverse('blog_detail', args=[self.id]) when I submit my form data don't save I want author auto quantification if blog_form.is_valid(): new_form = blog_form.save(commit=False) new_form.author = request.user new_form.save() return redirect('blog_list') else: print('bug is here') I tried that and printed bug is here (when try from admin panel everything is right) -
Reverse for 'car_details' with arguments '('',)' not found. 1 pattern(s) tried:
In Views.py def car_details(request, id): redirect_to=1 single_car = get_object_or_404(Car, pk=id), id = 1 data = { 'single_car': single_car, # 'url': url, } reverse('single_car', args=(id)) return render(request, 'cars/car_details.html', data) In urls.py of my app urlpatterns = \[ path('', views.cars, name='cars'), path('\<int:id\>/car_details', views.car_details, name='car_details'), \] and In my templates cars.html for car in cars %}`your text` <h1> <a href="{% url ">{{car.car_title}}</a> </h1> <a href="{% url "> {{car.state}}, {{car.city}} </a> endfor %} when i tried to call this car_details.html with urls function it show me this error Reverse for 'car_details' with arguments '('',)' not found. 1 pattern(s) tried: I also tried with reverse function it doesnot work,How can I solve this error in models.py class Car(models.Model): id=models.IntegerField(primary_key=True,default=True) def __str__(self): return self.car_title Reverse for 'car_details' with arguments '('',)' not found. 1 pattern(s) tried: and I tried to call the Templates in my urls in a loop but shows me this error -
Custom user model in Django and super user
I am using Django as backend for my mobile app. When creating users info I need the following info:name, DoB and firebaseUID. Please note that I do not want their email or password. But I want to create superusers who act as admins and want the superusers to be created using email and password. So I am not sure if I have to: Create a custom user by extending AbstractBaseUser and have a user manager attached to that custom user OR Create a custom user by extending AbstractBaseUser and then create another Django user class which is only for superusers. I implemented option 1 with the below code, but I get the following error: "TypeError: MyUserManager.create_superuser() missing 1 required positional argument: 'email'" Also when I am creating superuser, Django is asking for name, firebaseUID and DOB fields although I want to create superusers only email and password fields. from django.contrib.auth.models import AbstractBaseUser from django.db import models from django.utils import timezone class MyUserManager(models.Manager): def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return … -
ValueError at /users/register/ The view users.views.register didn't return an HttpResponse object. It returned None instead
I am getting this error ValueError at /users/register/ The view users.views.register didn't return an HttpResponse object. It returned None instead. I am using Django to complete the registration form, however I was unable to eliminate this problem. def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() return render(request,'users/register_done.html') else: user_form = UserRegistrationForm() return render(request,'users/register.html',{'user_form':user_form}) This is my views.py file made a register function with the return render. path('register/',views.register,name='register'), this is urls py Is there any other solution to come over My result Output I am expecting the solution for my problem -
my django file requirement.txt is installing while running in docker through cmd on my Window 10
Dockerfile FROM python:3.8-slim-buster WORKDIR /main COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD python manage.py runserver In my cmd/terminal: E:\Satya_Django_TODO_APP\todo>docker build -t my_image --rm . [+] Building 95.5s (8/9) => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 32B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/python:3.8-slim-buster 2.2s => [1/5] FROM docker.io/library/python:3.8-slim-buster@sha256:0b92aced9b0e52b16870a7c09 0.0s => [internal] load build context 0.1s => => transferring context: 28.89kB 0.0s => CACHED [2/5] WORKDIR /main 0.0s => CACHED [3/5] COPY requirements.txt requirements.txt 0.0s => ERROR [4/5] RUN pip3 install -r requirements.txt 93.0s [4/5] RUN pip3 install -r requirements.txt: #8 13.02 WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f04029205e0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/aioredis/ #8 15.23 Collecting aioredis==1.3.1 #8 25.24 WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f0402d7c4c0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /packages/b0/64/1b1612d0a104f21f80eb4c6e1b6075f2e6aba8e228f46f229cfd3fdac859/aioredis-1.3.1-py3-none-any.whl #8 35.75 WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f0402d7c730>: Failed to establish a new … -
SMTPConnectError at /reset-password/
I am trying to create a password reset function for an app i am working on and i keep getting these error Traceback (most recent call last): File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/contrib/auth/views.py", line 242, in dispatch return super().dispatch(*args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/views/generic/edit.py", line 153, in post return self.form_valid(form) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/contrib/auth/views.py", line 255, in form_valid form.save(**opts) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/contrib/auth/forms.py", line 343, in save self.send_mail( File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/contrib/auth/forms.py", line 284, in send_mail email_message.send() File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 80, in open self.connection = self.connection_class( File "/home/dubsy/anaconda3/lib/python3.9/smtplib.py", line 258, in __init__ raise SMTPConnectError(code, msg) Exception Type: SMTPConnectError at /reset-password/ Exception Value: (421, b'Service not available') here is my config in settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "abcdefgh@gmail.com" EMAIL_HOST_PASSWORD = "lssbjcfdthbfsbnx" I have enabled 2-Step Verification … -
TypeError: unhashable type: 'Path' (Importing any package)
I've got a weird one here. I've setup a mini Django project, and in the urls.py file, if I try any "from package import X", it results in an exception: TypeError: unhashable type: 'Path' With no imports in this file, it all works perfectly and the server starts etc. File "/app/app/urls.py", line 2, in <module> 2023-01-21T04:41:15.890469838Z from rest_framework.response import Response 2023-01-21T04:41:15.890486088Z File "/usr/local/lib/python3.8/site-packages/rest_framework/response.py", line 11, in <module> 2023-01-21T04:41:15.890490338Z from rest_framework.serializers import Serializer 2023-01-21T04:41:15.890492504Z File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 27, in <module> 2023-01-21T04:41:15.890516629Z from rest_framework.compat import postgres_fields 2023-01-21T04:41:15.890534421Z File "/usr/local/lib/python3.8/site-packages/rest_framework/compat.py", line 33, in <module> 2023-01-21T04:41:15.890571546Z import coreapi 2023-01-21T04:41:15.890591004Z File "/usr/local/lib/python3.8/site-packages/coreapi/__init__.py", line 2, in <module> 2023-01-21T04:41:15.890598088Z from coreapi import auth, codecs, exceptions, transports, utils 2023-01-21T04:41:15.890600588Z File "/usr/local/lib/python3.8/site-packages/coreapi/auth.py", line 1, in <module> 2023-01-21T04:41:15.890602963Z from coreapi.utils import domain_matches 2023-01-21T04:41:15.890605254Z File "/usr/local/lib/python3.8/site-packages/coreapi/utils.py", line 5, in <module> 2023-01-21T04:41:15.890724213Z import pkg_resources 2023-01-21T04:41:15.890736088Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3249, in <module> 2023-01-21T04:41:15.891071296Z def _initialize_master_working_set(): 2023-01-21T04:41:15.891081671Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3223, in _call_aside 2023-01-21T04:41:15.891363838Z f(*args, **kwargs) 2023-01-21T04:41:15.891371088Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3261, in _initialize_master_working_set 2023-01-21T04:41:15.891722921Z working_set = WorkingSet._build_master() 2023-01-21T04:41:15.891733421Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 608, in _build_master 2023-01-21T04:41:15.891780379Z ws = cls() 2023-01-21T04:41:15.891790796Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 601, in __init__ 2023-01-21T04:41:15.891883463Z self.add_entry(entry) 2023-01-21T04:41:15.891889546Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 655, in add_entry 2023-01-21T04:41:15.892080713Z self.entry_keys.setdefault(entry, []) 2023-01-21T04:41:15.892097713Z TypeError: unhashable type: 'Path' This is … -
How rename input class in crispy-form Dlango
How rename input class "numberinput form-control"? <input type="number" name="sq" step="0.1" class="numberinput form-control" required="" id="id_sq"> I can rename div class, lable class, but not input class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ["file", "sq", "rent_tax"] Template <div class="form-group col-md-6 mb-0"> {{ form_project.sq|as_crispy_field }} </div> -
how test try except with pytest and coverage in django?
Hello i hope you are great. Here I want to drag an Attribute called file_validator_error_message from the Django settings, how to write a test using Pytest a test that is valid for coverage . try: # Get Error Message From Django Setting ERROR_MESSAGE = settings.FILE_VALIDATOR_ERROR_MESSAGE except AttributeError: ERROR_MESSAGE = "{file} is not valid" except ImproperlyConfigured: ERROR_MESSAGE = "{file} is not valid" How to write a test code for this piece? -
How to select data from two different models and save it on another model in DRF?
I am new to Django. I want to hit a single API which will select data from two different models and will save data on some other table. e.g. querset1 = Model1.objects.filter( id__in={x.id for x in self.request.user.user_modules}) queryset2 = Model2.objects.filter( organization=self.request.user.organization ) Based on the data selected from these two querysets, I want to save it in third table. e.g. obj = Model3(data1=data1_selected, data2=data2_selected) How to do this by writing a single ModelViewSEt? -
.objects.all() query not showing all data
I am new to Django and I am trying to access all objects using: user_info.objects.all() but it is giving query set of overall object Here is the image that I get when I run Query in Django in terminal. -
how to initialize input form fields using URL parameters [django]
I can't set the input field values using the URL The form needs to be filled with data from the URL I tried initial= but it does not work. am I missing something views.py from django.shortcuts import render, redirect from django.http import HttpResponse, request, response from django.forms import formset_factory from django.forms import inlineformset_factory from .models import Participant, CheckingStatus from .forms import BookForm, ParticipantFormSet def form_view(request): if request.method == 'POST': form = BookForm(request.POST) formset = ParticipantFormSet(request.POST) if form.is_valid() and formset.is_valid(): book = form.save() formset.instance = book formset.save() else: form = BookForm() initial_data = request.GET.copy() formset = ParticipantFormSet(initial=[initial_data]) return render(request, 'form.html', {'form': form, 'formset': formset}) -
Django forms - display HTML <pre> code snippets within rendered {{ form.text }}
I have a blog set up with Django that I use to post some of my notes and personal how-tos. I have an articles model that takes data from a form rendered in the template. The application displays my articles posted dynamically in the template. My goal is to include code snippets as a <pre> tag within the form data that I post, while writing as little HTML as possible. models.py from django.db import models from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Article class ArticleListView(LoginRequiredMixin, ListView): model = Article template_name = 'article_list.html' class ArticleCreateView(LoginRequiredMixin, CreateView): model = Article template_name = 'article_new.html' fields = ('title', 'body',) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) templates/article_new.html {% extends 'base.html' %} {% block title %}New article{% endblock title %} {% block content %} <h1>New article</h1> <form action='' method='post'> {% csrf_token %} {{ form.as_p }} … -
Django Rest Framework how do I get the id I use in the URL
I have this serializer and I use it to get post detail of a post belonging to a user. The owner of the post is not the user that is currently logged in. I want to check if the post is bookmarked by the currently logged in user. The currently logged in user's id is passed in the request but I cannot find it in this context. Here is the serializer: class UserPostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True, required=False) profile = serializers.SerializerMethodField() bookmarked = serializers.SerializerMethodField() class Meta: model = Post fields = [ "id", "category", "body", "images", "video", "profile", "published", "bookmarked", "created_at", "updated_at", ] depth=1 def get_profile(self, obj): profile_obj = Profile.objects.get(id=obj.user.profile.id) profile = ShortProfileSerializer(profile_obj) return profile.data def get_bookmarked(self, obj): breakpoint() bookmark = Bookmark.objects.filter(owner=obj.user.id, post=obj.id,marktype='post') if bookmark: return True else: return False The problem is obj.user.id is the owner of the post. I need the logged in user whose id is passed in the url. Here is the model for the bookmark: class Bookmark(models.Model): marktype = models.CharField(max_length=50) post = models.OneToOneField(Post, on_delete=models.CASCADE, null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "bookmark" verbose_name_plural = "bookmarks" ordering = ["created_at"] db_table = "bookmarks" def … -
Why does this test keep failing?
I'm trying to write a simple test for some endpoints but the second one keeps failing. Here's the test.py from rest_framework.test import APITestCase, APIRequestFactory from rest_framework import status from django.urls import reverse from .views import PostViewSet from django.contrib.auth import get_user_model User = get_user_model() class PostListCreateTestCase(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.view = PostViewSet.as_view({"get": "list", "post": "create"}) self.url = reverse("post_list") self.user = User.objects.create( email="testuser@gmail.com", name="testuser", password="pass" ) def test_list_posts(self): request = self.factory.get(self.url) response = self.view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_post(self): sample_post = { "title": "sample title", "body": "sample body", } request = self.factory.post(self.url, sample_post) request.user = self.user response = self.view(request) self.assertEqual(response.status_code, status.HTTP_201_CREATED) And here's the view: from rest_framework import viewsets, status from rest_framework.response import Response from django.shortcuts import get_object_or_404 from .serializers import PostSerializer, LikeSerializer from .models import Post, Like class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() def get_queryset(self): posts = Post.objects.all() return posts def get_object(self): post = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"]) self.check_object_permissions(self.request, post) return post def create(self, request, *args, **kwargs): try: post = Post.objects.create( title=request.data.get("title"), body=request.data.get("body"), author=request.user, ) post = PostSerializer(post) return Response(post.data, status=status.HTTP_201_CREATED) except Exception as ex: return Response(str(ex), status=status.HTTP_400_BAD_REQUEST) def list(self, request, *args, **kwargs): posts = self.get_queryset() serializer = self.get_serializer(posts, many=True) return Response( data=dict(posts=serializer.data, total=len(serializer.data)), status=status.HTTP_200_OK, ) That's what I get: … -
Way to show latest 4 blog posts on my page
I want to be able to show the latest 4 blog posts only. I can't seem to get them to show. Any help would be greatly appreciated. Here is my code: Models.py class BlogPost(models.Model): blog_title = models.CharField(max_length=48) blog_article = RichTextUploadingField(null=True, blank=True, default="ici") blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) blog_published = models.BooleanField(default=False) blog_featured = models.BooleanField(default=False) def publish(self): self.blog_date = timezone.now() self.save() def __str__(self): return self.blog_title Views.py def blogTest(request): posts = BlogPost.objects.filter(blog_date__lte=timezone.now()).order_by('blog_date') context_blog = {'posts': posts} return render(request, 'blogtest.html', context_blog) def latestPosts(request): latest = BlogPost.objects.filter(blog_date__lte=timezone.now()).reverse()[:3] return render(request, 'blogtest.html', {'latest': latest}) Template <div class="blog-post-container"> <div class="row"> <h1 id="lastest-blogs-title" style="text-align: center;">Latest Blogs</h1> {% for latestpost in latest %} {% if latestpost.blog_published is True %} <div class="col-md-4" id="bloggrid1"> <hr> <div class="blog-post"> <div class="blog-content"> <img class="blog-img"src="{{latestpost.blog_image.url}}"alt="My image"/> <h2 class="blog-title">{{latestpost.blog_title}}</h2> <hr id="blog-hr" style="width: 90%" /> <article class="blog-article"> <p>{{latestpost.blog_article|truncatechars_html:265|safe}}</p> </article> <a href="{% url 'viewblog' post.id %}"class="btn btn-secondary"type="button"class="blog-button">Read More...</a> <p class="blog-date">Posted on: {{latestpost.blog_date}}</p> </div> </div> </div> {% endif %} {% empty %} <h3>No Blog Uploads</h3> {% endfor %} </div> </div> </div> I have followed many other tutorials but I can't seem to see what I'm doing wrong here. -
Rollup Not Tree Shaking D3.js Correctly, Even With sideEffects Flag Set To False?
When using rollup v3 to bundle my npm project that uses the D3.js v7 library to an es6 module for use on the browser, I am ending up with a lot of extra unnecessary code from D3.js in the produced bundle. This happens even with the sideEffects flag set to false in package.json, which seemed to be the solution to this issue when it was discussed a couple of years ago on this github issue: https://github.com/d3/d3/issues/3076 . While treeshaking is definitely occuring, I'm still ending up with almost 1000 lines of code in my bundle from just importing one function (select from d3-selection). Besides setting the sideEffects flag to false in package.json, is there anything else I need to do? I also tried setting moduleSideEffects to false in rollup.config, but this didn't seem to have any additional effect. I have created a very simple example npm project that reproduces the issue. It is on github here: https://github.com/SpechtacularDave/rollupd3treeshake , or you can view the the example input index.js, package.json, and rollup.config.js below (but see the repo if you want to take a look at the output bundle since it's almost 1000 lines long). // index.js import {select} from "d3-selection"; select('#someid'); // … -
How are environment variables processed from ".env" file if Django project deployed to AWS from Github?
I have a Django project deployed on AWS EBS from a Github repo. My secret key is kept on a .env file. I've included the following: settings.py from decouple import config "SECRET_KEY" = config.("MY_SECRET_KEY") requirements.txt python-decouple==3.7 .env MY_SECRET_KEY = "THISISMYSECRETKEY-THISISMYSECRETKEY-THISISMYSECRETKEY" Since I've include .env inside my .gitignore file, the .env is not being pushed to Github. When I try to deploy my project I keep getting an error: "web: decouple.UndefinedValueError: SECRET_KEY not found". The project runs fine on a local server. Any advice would be appreciated. -
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
I have an issue with my container. I tried to Dockerize my django project and now i get some errors that i cannot resolve this is my Dockerfile FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN apt-get update && apt-get install -y libpq-dev RUN apt-get update && apt-get install -y python3-psycopg2 RUN pip3 install Psycopg2-binary RUN pip install --upgrade pip && pip install -r requirements.txt COPY . /code/` this is my 'docker-compose.yml' version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - localhost localhost: image: postgres:10 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=Dimitri98! - POSTGRES_DB=test_DB_IS volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" volumes: postgres_data: But my command 'docker-compose up --build' with this output : mbakop_polls-web-1 | connection = Database.connect(**conn_params) mbakop_polls-web-1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect mbakop_polls-web-1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) mbakop_polls-web-1 | django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused mbakop_polls-web-1 | Is the server running on that host and accepting TCP/IP connections? mbakop_polls-web-1 | connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address mbakop_polls-web-1 | Is the server running on that host and accepting TCP/IP … -
How could I configure it so that the user who is logging in is a user of a PostgreSQL database manager?
I am developing a web application, I would like to know how I can configure it so that the user who is logging in is a user of the PostgreSQL database manager, generally there is a superuser who has permissions to freely manage all the databases, but other users with a lower hierarchy can be added, so I would like it to be possible to access as such with those users created in the DBMS. I use python as programming language and django as framework. I really have no idea how to achieve this functionality, I'm starting my studies, I want to surprise my database teacher with something different from the rest of the students, and I would like someone to help me with this, I don't expect a complete solution, just a guide and references to be able to achieve what is proposed