Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I send verification email on Django when user update email id using signals.py
how can I send verification emails on django using signals.py when a user updates the email id on the Custom profile model? This is my signals.py for updating the User model. I want to send a confirmation email when the user updates their email id. @receiver(post_save, sender=models.Profile_user) def update_auth_user_model_handler(sender, instance, created, **kwargs): if created: return user_instance = instance.user user_instance.first_name = instance.first_name user_instance.last_name = instance.last_name user_instance.email = instance.email user_instance.save() I want to send confirmation email to the new email when an user updates his email id before saving it to the User model on Django -
is there an efficient way of preventing the same email addresses registered with the different capitalizations sign up in django?
In views.py if User.objects.filter(email = email).exists(): messages.info(request, 'Email already in use') return redirect('signup') Django only checks if the exact email with the exact capitalization exists so for example if there is johndoe@yahoo.com in the user object and I signup with jOHNDoe@yahoo.com instead of telling it that email already in use it creates another user for the gmail with it's unique capitalization. admin user panel -
How to delete follow id base on both user_id and following_user_id using Django Rest Framework?
Okay, here's the thing I'm already able to create userfollowing relationship based on both the current user(user_id) and the user that is being followed (following_user_id). But what I want to do is to be able to delete a specific user_id and following_user_id following relationship by the id that was generated when the relationship was first established. Here's my code for better understanding. Thanks in advance for your help, which I will really appreciate. My UserFollowing Model class UserFollowing(models.Model): user_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="following") following_user_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="followers") created = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint(fields=['user_id','following_user_id'], name="unique_followers") ] ordering = ["-created"] def __str__(self): return f"{self.user_id.name} follows {self.following_user_id.name}" My UserFollowing Views class UserFollowingView(generics.ListCreateAPIView): # permission_classes = (IsAuthenticatedOrReadOnly,) serializer_class = UserFollowingSerializer queryset = UserFollowing.objects.all() class DeleteFollowView(generics.RetrieveDestroyAPIView): # permission_classes = (IsAuthenticatedOrReadOnly,) serializer_class = UserFollowingSerializer queryset = UserFollowing.objects.all() -
Page not found 404 django
Tengo este problema enter image description here y no se que hacer, he intentado algunas cosas pero no ha funcionado. Este es el archivo urls.py: enter image description here Creo que el problema esta en ese archivo pero no sabría como solucionarlo -
IntegrityError at /signup/ UNIQUE constraint failed: accountss_doctor.user_id
I'm trying to signup as Doctor but I got the following issue . raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: accountss_doctor.user_id this is my models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) last_login = models.DateTimeField(auto_now_add=True) name = models.CharField(_('الاسم :'), max_length=50) surname = models.CharField(_(' اللقب :'), max_length=50) subtitle = models.CharField(_('نبدة عنك :'), max_length=50) address = models.CharField(_("المحافضة :"), max_length=50) this is my views.py class DoctorSignupForms(UserCreationForm): username = forms.CharField(label="الاسم") first_name = forms.CharField(label="الاسم الاول") last_name = forms.CharField(label=" الاسم الاخير") number_phone = forms.CharField(label=" الهاتف") email = forms.EmailField(label="البريد الالكتروني") password1 = forms.CharField( label=" كلمة المرور", widget=forms.PasswordInput(), min_length=8) password2 = forms.CharField( label="تاكيد كلمة المرور", widget=forms.PasswordInput(), min_length=8) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'number_phone') @transaction.atomic def save(self): user = super().save(commit=False) user.email = self.cleaned_data.get('email') user.is_doctor = True user.save() doctor = Doctor.objects.create(user=user) doctor.username = self.cleaned_data.get('username') doctor.number_phone = self.cleaned_data.get('number_phone') doctor.save() return doctor I heard that it's because of the relation which it has to be foreinkey instead of one to one but I want every doctor have … -
reset id whenever a row deleted in django
i wanted to start id from 1 . whenever a row deleted it skips that number and jump to next number. like in this image it skips number from 1-6 and 8. i want to set it as 1,2,3 this is my models.py class dish(models.Model): id = models.AutoField(primary_key=True) dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) # dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to. dish_date = models.DateField() def __str__(self): return self.dish_name this is views.py def delete(request, id): dishs = dish.objects.get(id=id) dishs.delete() return HttpResponseRedirect(reverse('check')) -
How can I delete all user data when deleting profile on Django using signals.py
how can I delete all user data when deleting a user profile on Django using signals.py? I am trying to delete a custom user model using Django and when the profile is deleted I want to delete all data of that user using signals.py how can I create it? @receiver(post_delete, sender=models.Profile_user) def delete_auth_user_model_handler(sender, instance, *args, **kwargs): user_instance = instance.user user_instance.delete() I want to delete blogs of the user-written when the profile is deleted -
DRF - How to using serializer to load related data
I have a self related table Employee, and Project table has foreignkey to related to Employee table. class Employee(models.Model): eid = models.CharField(primary_key=True, max_length=10) name = models.CharField(max_length=10) pmid = models.ForeignKey('self', models.RESTRICT, related_name='team_member', blank=True, null=True,) class Project(models.Model): pid = models.CharField(primary_key=True, max_length=10) description = models.CharField(max_length=100) teamleaderid = models.ForeignKey(Employee, models.RESTRICT) and serializers.py class SubEmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): team_member = SubEmployeeSerializer(many=True, read_only=True) class Meta: model = Employee fields = '__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' depth = 1 views.py class ProjectList(generics.ListAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer I hope when request ProjectListView I can get teamleaderid with team_member data but I don't know why team_member not show in my response. [ { "pid": "p1", "description": "p1 project", "teamleaderid": { "eid": "1", "name": "n1", "pmid": null, ###### how to show below data ### # "team_member": [ # # { # # "eid": "5", # # "name": "n5", # # "pmid": "1" # #} # ################################# } } ] -
How to remove or disable unwanted languages in Django 4.1.1
I had a question about translations in Django... So I have a project with 4 languages defined in my settings.py LANGUAGES = [ ('en', _('English')), ('fr', _('French')), ('de', _('German')), ('it', _('Italy')), ] now I want to disable all languages except english, so I've been searching in google how to do it, and find this post on SO => enter link description here, than I tried to comment all languages except english, after that I've done ./manage.py makemigrations => ./manage.py migrate migrations went without any error, BUT in my language list they didn't dissapear... also I've been find code that as I think forms this list... I changed thare hardcoded langlist from language_list = ['en', 'it', 'de', 'fr'] to language_list = settings.LANGUAGES and also nothing happened with my UI language list choices... So, question: how properly I can disable unwanted languages in my Django application; P.S I'm new in python and Django at all, so please can anyone help me with this? -
400 bad request in "POST" request in django react
i have react component in were im posting data in djnago back end. but it always gives me 400 bad request as response and in backend console too. here is my code. ` import axios from 'axios' import React, { useEffect, useState } from 'react' import { Button } from 'react-bootstrap' import API_URL from './BackendDefaustUrls'; import {useNavigate, useParams} from "react-router-dom" const AddProduct = () => { const [Image , setImage] = useState(null) const [Name , setName] = useState("") const [Price , setPrice] = useState("") const [Description , setDescription] = useState("") const [Category , setCategory] = useState("") const navigate = useNavigate() const {id} = useParams() const getProduct = async () => { await axios.get(API_URL+`api/${id}/`).then(response => { return response.data }).then(data => { setName(data.name) setImage(data.image) setPrice(data.price) setDescription(data.description) setCategory(data.category) }) } useEffect(()=>{ getProduct() },[]) const AddProductInfo = async () =>{ let formField = new FormData() formField.append('name',Name) formField.append('price',Price) formField.append('description',Description) formField.append('category',Category) if (Image != null) { formField.append('image',Image) } await axios({ method: 'POST', url: API_URL + `api/`, data:formField }).then(response => { console.log(response.data); navigate("/") }) } return ( <div> <div className='container'> <div className="w-75 mx-auto shadow p-5"> <h2 className="text-center mb-4">Add A Student</h2> <div className='form-group'> {/* image */} <label>Select Image To Upload</label> <input type="file" name="image" className='form-control form-control-lg' onChange={e=>setImage(e.target.files[0])} /> </div> … -
How to add message box to admin panel
I have added my custom action that performs sending message to users. But I don't know how can I put my message where. So how can I add message field to my admin panel and connect to my custom action button? -
Django; Can't Access to Other Models inlineformset_factory Fields
I have a successfully working inlineformset_factory form. I create this model with a button and inherit the data in it from another model. However, I was not able to access the inlineformset_factory fields in the other model. def create_offer_button(request): if request.method == "POST": post = request.POST.get("post_pk") obj = RequestModel.objects.get(pk=post) if obj.is_accepted: OfferModel.objects.create(request_model_name=obj, request_title=obj.request_title, delivery_time=obj.delivery_time, shipping_country=obj.shipping_country, shipping_address=obj.shipping_address, preferred_currency=obj.preferred_currency, shipping_term=obj.shipping_term, delivery_term=obj.delivery_term) obj.is_offer_created = True obj.save() return redirect(request.META.get("HTTP_REFERER")) How can i access to RequestModel's inlineformset_factory fields? I tried many methods but I could not reach the formset fields of the inheritance model. -
Django: Object is not saved to DB when submitting form with CreateView
I have a CreateView to create artists but when submitting the form, nothing happens. models.py class Artist(models.Model): name = models.CharField(max_length=222, unique=True) slug = models.SlugField(unique=True, null=True) age = models.PositiveIntegerField(null=True,blank=True) location = models.CharField(max_length=222, null=True, blank=True) bio = models.TextField(null=True,blank=True) booking_fee_per_hour = models.PositiveIntegerField(verbose_name="Booking Fee per hour") def __str__(self): return self.name views.py class ArtistsAddView(views.CreateView): template_name = 'add_artist.html' model = Artist fields = '__all__' success_url = '/' templates -> add-artist.html <form method="post" action="{% url 'artist add' %}"> <p>{{ form.name.label_tag }} {{ form.name }}</p> <p>{{ form.age.label_tag }} {{ form.age }}</p> <p>{{ form.location.label_tag }} {{ form.location }}</p> <p>{{ form.bio.label_tag }} {{ form.bio }}</p> <input type="hidden" name="next" value="{{ next }}"> <button>Submit</button> {% csrf_token %} </form> I intentionally hid 2 of the fields: slug and booking_fee_per_hour. I would like to make them available only for admins. If I write: <form method="post" action="{% url 'artist add' %}"> {{ form.as_p }} <input type="hidden" name="next" value="{{ next }}"> <button>Submit</button> {% csrf_token %} </form> then the artist is saved to the DB but also the normal user can see slug and booking_fee_per_hour. Could you please help me? -
TinyMCE referer header missing in Django
I am using TinyMCE to write text with markup in my Django project. Im am displaying the TinyMCE editor on a user page where they can type text with markup. This works just fine. However: The editor prompts the following message when displaying the page: We’re unable to check your domain because the referer header is missing. Please read the Guide on how to ensure your referer header is present, so we can then customize your editor experience. I can't seem to figure out what is missing and how to fix it. Any help would be much appreciated! In my models I implement the TinyMCE as follows: bottle_info = HTMLField() -
How to Override CreateModelMixin corrctly
I want to override CreateModelMixin with my own class which derived from ModelViewSet this is the class i want to override class CreateModelMixin: """ Create a model instance. """ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': str(data[api_settings.URL_FIELD_NAME])} except (TypeError, KeyError): return {} in the first instinct, I want to override only the create function with a different serializer but would it be more correct to override perform_create? if someone can guide me how it is the most correct way to override that will be much of help thank you -
How can i pass validated data to another custom validator class in DRF?
I Have this kind of serializer.py class PostSerializer(serializers.ModelSerializer): title = serializers.CharField(validators=[TitleValidator()]) slug = serializers.CharField(validators=[SlugsValidator()], max_length=100, required=False) and i have two class validators for this fields class TitleValidator: MIN_TITLE_LENGTH = 20 def __call__(self, title: str): if len(title) < self.MIN_TITLE_LENGTH: raise ValidationError(f"Min title length is {self.MIN_TITLE_LENGTH}") return title class SlugsValidator: def __call__(self, slug): # Get title here return slug How can I pass the validated title into SlugValidator class? I've tried to pass data directly to the TitleValidator instance, but the only thing I can get is the field itself, not an actual value. Another way was to pass data inside validate() method, but seems like custom class validators are executed first, and i' getting an error that the title argument is not provided. Is there any way I can achieve this? -
Bootstrap 5.0 Navbar Dropdown not working
I couldn't make the dropdown on my navbar work. When I click on it nothing happens. What might be the problem? I checked similar posts but couldn't find a solution. Am I missing a script or something? layout.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <body> <nav class="navbar" style="background-color: #e6e2c2;"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <img src="{% static 'potbs/potbs.png' %}" alt="Logo" width="50" height="30" class="d-inline-block align-text-top"> Pat on the Back Studios. </a> <div class="navbar-expand" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Profile </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Profile</a></li> <li><a class="dropdown-item" href="#">Earned Badges</a></li> <li><hr class="dropdown-divider"></li> <li><a class="nav-link" href="{% url 'logout' %}">Log Out</a></li> </ul> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> </li> {% endif %} </ul> </div> </div> </nav> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script> </body> </html> -
How to send JWT REFRESH TOKEN as http only cookie in django?
I am using Django(REST FrameWork, SimpleJWT) and React for my project. For autentication I am using JWT method. According to some articles, storing and sending REFRESH TOKEN in HttpOnly Cookie is the a best and secure way. Since I am learning WebDevelopment I can't able to find any source to about it. This is my views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer def post(self, request, *args, **kwargs): try: response = super().post(request) except InvalidToken: return Response({'Invalid or expired token'}) refresh_token = RefreshToken.for_user(request.user) response.set_cookie('refresh_token', refresh_token, httponly=True) return response class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer class LogoutView(generics.CreateAPIView): def post(self, request): refresh_token = request.data['refresh_token'] token = RefreshToken(refresh_token) token.blacklist() return Response({'Logout':'Successfullly'}) as you can i even tried to over write the post method in MyTokenObtainPairView. This is my urls.py path('api/login/', MyTokenObtainPairView.as_view(), name="token_obtain_pair"), path('api/token/refresh/', TokenRefreshView.as_view(), name="token_refresh"), path('api/register/', RegisterView.as_view(), name="auth_register"), path('api/logout/', LogoutView.as_view(), name="logout"), This is my settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(hours=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=2), } I am expecting a way to … -
API to get all pincodes inside a radius
I'm working on a python application where we need to get all the pincodes within a specific radius. We have a base location and a radius of 10Km is drawn from this base pincode. Do we have any API where this can be achieved? FYA - Mainly looking for Indian PostalCodes. -
How to customize django loginview
path('account/login', auth_views.LoginView.as_view(template_name='main/log_form.html'), name='login'), path('account/logout/', auth_views.LogoutView.as_view(template_name='main/logout.html'), name='logout'), How to customize django loginView? -
Django comment not saving to post
Comments are saving to DB but not linking to Post, unless I manually go to Admin page and link. MODELS.PY class Post(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=50) info = models.TextField(max_length=2000) slug = models.SlugField(null=True, unique=True, max_length=300) created = models.DateField(null=True, auto_now_add=True) approved = models.BooleanField(default=False, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50, verbose_name="Name") comment = models.TextField(max_length=500, verbose_name="Review") created = models.DateField(null=True, auto_now_add=True) approved = models.BooleanField(default=False, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) FORMS.PY class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name','comment'] VIEWS.PY def create_comment(request, slug): form = CommentForm() post = Post.objects.get(slug=slug) if request.method == "POST": form = CommentForm(request.POST) comment = form.save() review.post = post review.save() messages.success(request, 'Your comment was successfully submitted!') return render(request, 'post.html', {'post': post, 'form':form}) return render(request, 'post.html', {'post': post, 'form':form}) From Admin page I can add comment and manually link to post, but from frontend form, comment is created and saved to DB but not linked to any post -
django rest framework Convert a view to api
I am a beginner in drf and I need to create this view in drf, but I don't know what method I should use. class CategoryList(ListView): template_name = "blog/categorylist.html" paginate_by = 10 def get_queryset(self): global my_category slug = self.kwargs.get('slug') my_category = get_object_or_404(Category, slug=slug) return my_category.articles.published() def get_context_data(self, **kwargs): context = super(CategoryList, self).get_context_data(**kwargs) context['category'] = my_category return context -
How to write test for Django image url
I'm writing my first test as a Django developer. How do I write a test for the image property of this model shown below class Project(models.Model): engineer = models.ForeignKey(Engineer, on_delete=models.CASCADE) name = models.CharField(max_length=100) tech_used = models.CharField(max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(default="project.png") description = models.TextField(null=True, blank=True) repo_url = models.URLField(null=True, blank=True) live_url = models.URLField(null=True, blank=True) make_public = models.BooleanField(default=False) def __str__(self): return self.name @property def image_url(self): try: url = self.image.url except: url = "" return url class Meta: ordering = ["-created"] I have tried to conjure some patches from here and there although I don't fully understand what my test.py code I just thought to include it to my question to show my efforts class TestModels(TestCase): def setUp(self): new_image = BytesIO() self.image = Project.objects.create( image=ImageFile(new_image) ) def test_image_url(self): self.assertEquals(self.image.image_url, '') Please a help on the above question and an explanation of whatever code given as help will be highly appreciated. -
How to process two GET requests, at the same time and collect the data in javascript
Hello I have a question and a doubt, I am in a view, when I give a button I do the following code function pagar_recibo(id) { $.ajax ({ delay: 250, type: 'GET', url: '/general/recibo/add', data: { 'id': id, 'action_al': 'add_alumnos', }, }); }; This button is a href that goes to another url, that is to say it makes another request to the server with GET then in the new view in the get_context_data I have the following def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['arg'] = json.dumps(self.alum()) # context['arg'] = self.alum() return context and the function is as follows def alum(self, **kwargs): data = [] try: action = self.request.GET.get('action_al', False) print(action) if action == False: return elif action == 'add_alumnos': data = [] id = int(self.request.GET['id']) Alumnos = Alumno.objects.filter(pk=id) for i in Alumnos: item = i.toJSON() item['text'] = i.get_full_name() data.append(item) print(data) except Exception as e: data['error'] = str(e) return data This is how I pick it up in the template window.data = {{ arg|safe }}; The problem is that one GET request is empty, the url change and the other is the ajax request with the given key and value, but I always get empty windows data, how could I … -
How to paginate comments for detail_view?
I'm writing a simple blog and I need paginate comments for each posts but I don't know how to do it. Thanks for help! There is my models: class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) short_description = models.CharField(max_length=230, default='Post') text = models.TextField() is_published = models.BooleanField(default=False) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) username = models.CharField(max_length=35) comment = models.CharField(max_length=120) is_published = models.BooleanField(default=False) def __str__(self): return self.comment There is my views: class PostDetail(generic.DetailView): template_name = 'user/post.html' model = Post def comment_view(request, pk): form = CommentCreateForm() if request.method == 'POST': form = CommentCreateForm(request.POST) if form.is_valid(): username = request.user comment = form.cleaned_data['comment'] Comment.objects.create(username=username, comment=comment, post_id=pk) return redirect('PostDetail', pk) return render(request, 'user/comment_view.html', {'form': form}) And there is my template: { object.title }} {% if object.author.id %} <a href="{% url 'public_profile' object.author.id %}">{{ object.author }}</a> {% endif %} <p>{{ object.text }}</p> <h4>Comments</h4> {% for comment in object.comment_set.all %} {{ comment.username }} <p>{{ comment }}</p> {% endfor %} <p><a href="{% url 'comment_view' object.id %}">Leave comment</a></p> Is it real to paginate comments? How I should paginate comments in detail_view?