Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting No Response While using js function in html
I'm working on a practice project trying to create Social media clone using python and javascript everything is going well but just stuck on an error so here's my code first html <form onsubmit="createComment('{{p.id}}')" > <input id="comment_text{{p.id}}" type="text" placeholder="Write an Answer"> <input type="submit"> </form> js function createComment(f){ alert('c') fetch('/comment', { method : 'POST', body : JSON.stringify({ post_id : f, comment_text : document.querySelector(`#comment_text${f}`).value }) }) .then(response => response.json()) .then(data => { alert('succes') }) } django models class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="commenter") text = models.TextField(max_length=250) time_comment = models.DateTimeField(auto_now_add=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_post") likes = models.ManyToManyField(User, related_name="likes") timestamp = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=1000) img = models.ImageField(upload_to="post", blank=True, null=True) comment = models.ManyToManyField(Comments,related_name="post_comments") url & view @csrf_exempt def new_comment(request): data = json.loads(request.body) print(data) post = Post.objects.get(id=data['post_id']) comment = Comments( user= request.user, text=data['comment']) comment.save() post.comment.add(comment.id) return JsonResponse({'message' : 'Succes'}, status=201) URL path("comment", views.new_comment, name="comment") I have some other function to create new post and edit which work similar and they are working well and I have checked my django views and url are fine I can do it without fetch method -
How can i use Django-mptt?
I want to make a navigation through categories and subcategories in Django. I install django-mptt and now i get this error."type object 'Category' has no attribute '_mptt_meta' " models.py from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Category(models.Model): name=models.CharField(max_length=50) slug=models.SlugField(max_length=50, unique=True, help_text='Uniue Value product page url, created from name.') is_active=models.BooleanField(default=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) parent=TreeForeignKey('self',on_delete=models.CASCADE,null=True,blank=True, related_name='children') class MPTTMeta: order_insertion_by=['name'] thanks beforehand. -
Filter from 2 different tables using Django rest Framework
Good day, I am trying to filter data from 2 different tables which have a one to many relationships. I have products table and specification table. 1 product is related to many specification list. I dont have any problems getting all the information of the product including the specifications. I am also successful in filtering the products table, like filter by category and manufacturer. but I want to filter also based on the specifications while filtering the category/manufacturer. here is my models. class Products(models.Model): product_partnumber = models.CharField(max_length=255) image_link = models.URLField(default=None, blank=True, null=True) pdf_link = models.URLField() manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Products' class ProductSpecification(models.Model): product = models.ForeignKey(Products, related_name='specifications', on_delete=models.CASCADE) specification = models.ForeignKey(Specification, related_name='specification_name', on_delete=models.CASCADE) value = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) and this is my codes for api and filtering. As of now I am only successful on filtering on one table. I have no idea how I can also add the ProductSpecification model on my filter class. class NumberInFilter(filters.BaseInFilter, filters.NumberFilter): pass class ProductFilter(filters.FilterSet): manufacturer__in = NumberInFilter(field_name='manufacturer', lookup_expr='in') class Meta: model = Products fields = ['category', 'product_partnumber'] class ProductsView(viewsets.ModelViewSet): queryset = Products.objects.all() serializer_class = ProductsSerializers filter_backends = [filters.DjangoFilterBackend] … -
Make a Django model class whose one of the field value is calculated by other model's fields values and it must be present in my actual Database table
models.py from django.db import models class model_A(models.Model): value_1 = models.IntegerField() value_2 = models.FloatField() class model_B(modles.Model): value_3 = models.FloatField() @property def value_4(self): return (model_A.value_1 - model_B.value_2) admin.py from django.contrib import admin # Register your models here. from .models import model_A, model_B model_lst = [model_A, model_B] for i in model_lst: admin.site.register(i) I want model_B to have value_4 as separate column in database table(model_B) -
'zip' object has no attribute 'model' using django
I want to obtain the code and the description of the code on my search bar using Django. I am getting an error as "'zip' object has no attribute 'model'" How may I resolve this or is there another way of defining it. My codes are: views.py def display_majorheads(request): outputs = ProcessedOutputs.objects.all() year = outputs.first().finyear.finyear be_year = int(year.split('_')[1]) p_majors = ProcessedOutputs.objects.only('major_cd') majors = Major.objects.only('description').filter(major_cd__in=p_majors.values_list('major_cd', flat=True)).distinct().order_by("pk") processed_outputs = zip(majors,outputs) myFilter = ProcessedOutputsFilter(request.GET, queryset=processed_outputs) processed_outputs = myFilter.qs context = { 'processed_outputs':processed_outputs, 'be_year':be_year, 'myFilter':myFilter, } return render(request, 'website/mhead.html', context ) filters.py class ProcessedOutputsFilter(django_filters.FilterSet): class Meta: model = ProcessedOutputs fields = '__all__' exclude = ['finyear', 'ag_salary'] mhead.html <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </button> </form> models.py class ProcessedOutputs(models.Model): major_cd = models.OneToOneField(Major, models.DO_NOTHING, db_column='major_cd', primary_key=True) finyear = models.ForeignKey(Finyear, models.DO_NOTHING, db_column='finyear') ag_salary = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'processed_outputs' unique_together = (('major_cd', 'finyear'),) -
Add steps to a model entry in Django
I am currently learning Django and was asking myself how I could add substeps to an entry. Lets take a recipe-app for example: A recipe consists of one ore many steps. The user wants to enter a recipe and gets provided with three form fields: Recipe name, ingredients and the option to add many steps. So how can I implement the functionality to add a ingredient list of unknown length and to add a unknown number of steps? I only know how to give the functionality of single form entries. Thanks for your hard work here. -
I want to write my product name like this - my_productnam....more... | in django
{{i.Title |slice:"0:30"}}... If Name of item crosses the limit of max characters then "More..." button should be automatically placed at 31st character. -
Django Request is missing required authentication credential, 'status' :UNAUTHENTICATED
I'm trying to social login with google, user_info = requests.get( f"https://www.googleapis.com/userinfo/v2/me", headers={"Authorization": f"Bearer {access_token}"}, ) print(info.json()) {'error': {'code': 401, 'message': 'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.', 'status': 'UNAUTHENTICATED'}} using Django i wanna take user infomation and save my database and login how can i do? -
How to know action (HTTP method) type in DRF generic views?
When using ViewSets you can do self.action and get to know whether you are currently handling a GET or POST and such. How do you do the same with generic views like ListCreateAPIView? I want to return a different serializer context in get_serializer_context depending on the current HTTP method being called. How do I go about this? -
Pass a selection form to view in Django
I am making a feedback form with selection. But I got the error MultiValueDictKeyError when submitting the form. I tried changing the code in the views.py, it becomes hb_content=request.POST.get('hb_content', False). But when I checked the data, it only saves a False value. Could you help me please? Thank you in advance. models.py: CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ) class Feedback(models.Model): class Meta: db_table = 'feedback' get_latest_by = 'created' # healthbook hb_content = models.CharField(max_length=6, choices=CHOICES, default='None') forms.py: CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ) class FeedbackForm(forms.ModelForm): hb_content = forms.ChoiceField(choices=CHOICES, label="", initial='', widget=forms.Select(), required=True) views.py: def feedback(request): if request.method == 'POST': feedback_form = Feedback(hb_content=request.POST['hb_content']) feedback_form.save() return render(request, '../templates/home/feedback.html', {}) feedback.html <div class="main"> <h1>Feedback</h1> <form id="contact_form" action="{% url 'feedback' %}" method="POST"> {% csrf_token %} <div class="form-group"> <h2>HealthBook</h2> <label for="hb_content">1. あなたにとって有益な情報が得られると思いましたか。5段階で評価してください。 とてもそう思う⇔全くそう思わない</label> <select name="hb_content"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </form> -
Djoser login with token doesn't require x-csrf token,
I'm new to Django/Django Rest Framework and trying to create a login page using the djoser package. This is my sample code, im using vue.js: login(){ const auth_user = {}; axios.post('auth/token/login/', { username: this.username, password: this.password, }) .then((response) => { if (response.status == 200) { auth_user.auth_token = response.data.auth_token; window.localStorage.setItem('auth_user', JSON.stringify(auth_user)); location.replace(window.location.origin + '/dashboard'); } }) .catch((error) => { }); }, I've Created a Login form that directly post to '/token/login' url, and generate an auth token. Questions: Is this the right thing to do if your creating a login page?? I'm just curious why the URL '/token/login' doesn't require X-CSRF Token?? Thank you -
django foreign key selecting in html form
how to add ForeignKey selecting to html form omniva=models.ForeignKey(Omniva,on_delete=models.SET_NULL,blank=True,null=True,related_name='orders') how i can add this Foreign key selecting to html form -
How to use 2 models in 1 view django?
So I have a model class Question(models.Model): question = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.question def check_answer(self, choice): return self.choice_set.filter(id=choice.id, is_answer=True).exists() def get_answers(self): return self.choice_set.filter(is_answer=True) def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) and another model class Choice(models.Model): question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) is_answer = models.BooleanField(default=False) def __str__(self): return self.choice_text def get_absolute_url(self): return reverse('article_list') How can I display both of these in the same view OR is there a better way of doing this -
Length filter on django template doesnt seem to work
I am trying to use raw query instead of the ORM. However I am having trouble when i try to count all instances from MyTable. Below is the code from my view : problems_raw_count = MyModel.objects.raw('SELECT * FROM MyApp_MyTable') problems_count = list(problems_raw_count) And now the variable I am trying to implement on template side : {{ problems_count|length }} I know I could simply use MyModel.objects.all() but it does interest me to know why it is not actually working. Many thanks. Romain -
How can I join two model tables using username as primarykey?
class Cust_detail(models.Model): Firstname = models.CharField(max_length=30) Lastname = models.CharField(max_length=30) signup_Username = models.EmailField(max_length=40) signup_Password = models.CharField(max_length=15) On my signup page, I have a row names "Username" which is unique for every customer. I would like to connect the two tables together using Username as the primary key class Cust_addres(models.Model): Phone_no = models.CharField(max_length=10) house_no = models.CharField(max_length=50) username=models.ForeignKey(Cust_detail,related_name='Users', on_delete=models.CASCADE,null=True, blank=True) -
searching theough a nested JSON data with python
i have a sample json file from a webhook response and i will want to extract just two data set from the JSON how can i do that using python. assuming i want to get the subscription code, and plan code values. thanks in anticipation "event": "subscription.create", "data": { "domain": "test", "status": "active", "subscription_code": "SUB_vsyqdmlzble3uii", "amount": 50000, "cron_expression": "0 0 28 * *", "next_payment_date": "2016-05-19T07:00:00.000Z", "open_invoice": null, "createdAt": "2016-03-20T00:23:24.000Z", "plan": { "name": "Monthly retainer", "plan_code": "PLN_gx2wn530m0i3w3m", "description": null, "amount": 50000, "interval": "monthly", "send_invoices": true, "send_sms": true, "currency": "NGN" }, "authorization": { "authorization_code": "AUTH_96xphygz", "bin": "539983", "last4": "7357", "exp_month": "10", "exp_year": "2017", "card_type": "MASTERCARD DEBIT", "bank": "GTBANK", "country_code": "NG", "brand": "MASTERCARD" }, "customer": { "first_name": "BoJack", "last_name": "Horseman", "email": "bojack@horsinaround.com", "customer_code": "CUS_xnxdt6s1zg1f4nx", "phone": "", "metadata": {}, "risk_action": "default" }, "created_at": "2016-10-01T10:59:59.000Z" } } -
Comment is not adding after click on submit button
Comment is not adding after clicking it on Add comment, views.py @login_required def detail_view(request,id): data = Post.objects.get(id=id) comments = data.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = data new_comment.save() else: comment_form = CommentForm() context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, 'mains/show_more.html', context ) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE,related_name='comments') body = models.TextField() active = models.BooleanField(default=False) class Meta: ordering = ['created_at'] def __str__(self): return self.body forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) show_more.html ( This is the template of show_more, where i have inserted comments ) {% for comment in comments %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> <span class=" text-muted font-weight-normal"> {{ comment.created_at }} </span> </p> {{ comment.body | linebreaks }} </div> {% endfor %} </div> </div> <div class="col-md-8 card mb-4 mt-3 "> <div class="card-body"> <h3>Leave a comment</h3> <form method="post" style="margin-top: 1.3em;"> {{ comment_form.as_p }} {% csrf_token %} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form> I think the problem is in views. Please help me in this. I will really appreciate your Help. -
AttributeError: 'function' object has no attribute 'get_extra_actions'
I am new in django and I am creating api for checkcking email is exist or not. i got a AttributeError: 'function' object has no attribute 'get_extra_actions' This is my Views.py file class VerifyEmail(views.APIView): queryset = Customer.objects.all() serializer_class = EmailVerificationSerializer def post(self, request): email=request.data.get('email') try: user = Customer.objects.get(email= email) except: user = None if user != None: return Response({'error': 'email already exist.'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'user': user.id}, status=status.HTTP_200_OK) This is my Serializer.py class EmailVerificationSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255, min_length=3) class Meta: model = Customer fields = ['email'] This is my urls.py file router = routers.DefaultRouter() router.register(r'email-verify', VerifyEmail.as_view(), basename='email)verify') urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] -
How can I specific dynamic URL to redirect new users after OAuth in django?
I use OAuth system to login in my site. Everything works good, but I want redirect new user on the edit their profile page. When I connected GitHub OAuth I specified on their site where will redirect user: https://i.stack.imgur.com/ZLjbO.png But I need specific unique dynamically URL from html template: {% url 'profile_form' pk=user.profile.pk %} My view looks like this: def register(request, backend='django.contrib.auth.backends.ModelBackend'): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') messages.success(request, 'Вы успешно зарегистрировались') return redirect('profile_detail', pk=user.profile.pk) else: messages.error(request, 'Ошибка регистрации') else: form = UserRegisterForm() return render(request, 'news/register.html', {"form": form}) I tried something like this in my settings.py: from django.shortcuts import redirect ... LOGIN_REDIRECT_URL = redirect('profile_detail', pk=request.user.profile.pk) LOGOUT_REDIRECT_URL = '/' How can I write it down correctly? -
DRF's token authentication with Angular
I'm using django for backend and Angular for frontend and DRF for making api calls. I'm making a user login system but currently the user gets logged out on refreshing the page. For preventing this i'm using rest_framework.authtoken.models.Token for generating token's for each user and I'm returning this token in my api call but I've no idea how to use this token in Angular to keep the user logged in on refreshing the page? Here is my code: views.py from django.contrib.auth.models import User from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view from .serializers import LoginSerializer @api_view(['POST']) def loginUser(request): if request.method == 'POST': user_data = JSONParser().parse(request) user_serializer = LoginSerializer(data=user_data) data = {} if user_serializer.is_valid(): user = user_serializer.validated_data['user'] try: uid = User.objects.get( username=user['username']) if not uid.check_password(user['password']): raise Exception token = Token.objects.get(user=uid) data['token'] = token.key data['response'] = 'Successful login' return JsonResponse(data, status=status.HTTP_202_ACCEPTED) except: data['response'] = "Username or password does not exist" return JsonResponse(data, status=status.HTTP_401_UNAUTHORIZED) user.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { User } from '../models/user'; @Injectable({ providedIn: 'root', }) export class UserService { private login_url = 'http://127.0.0.1:8000/login/'; private signup_url = 'http://127.0.0.1:8000/signup/'; private … -
Get queryset in categorize form with having list of items in Django
My person Model is here: class person(models.Model): interests = models.ManyToManyField(Ineterest, default=None) and Interest Model: class Interest(models.Model): interest = models.CharField(max_length=100) and article Model is here: class Article(models.Model): category = models.ManyToManyField(Interest, default=None) I just want to filter articles in categorize form having a list of all articles related with it example is: [{'category': 'Finance', 'articles': ['article obj-1', 'article obj-2']}, {'category': 'Business', 'articles': ['article obj-1', 'article obj-2', 'article obj-3']}] -
Django MultiValueField with MultiWidget
My Django 3.1 app keeps a user identity card info like this: XA12345678 (XA is a series of a user identity card and 12345678 - its 8-digit number). But in a form, I want users to select the series from the dropdown list and enter the number in the text field. So, it seems appropriate to use a custom form field and widget based on MultiValueField and MultiWidget. Unfortunately, Django official documentation isn't much help. So far, I have found only a few up to date pieces of information from the other sources. What my present code looks like: #Custom field class SICField(forms.MultiValueField): widget = SICWidget def __init__(self, reg_ex, *, is_stripped=True, **kwargs): fields = ( forms.ChoiceField(), forms.RegexField(reg_ex, strip=is_stripped) ) super().__init__(fields, **kwargs) def compress(self, data_list): return ''.join(data_list) #Custom widget class SICWidget(forms.MultiWidget): template_name = 'widgets/sic_widget.html' def __init__(self, attrs=None, series_attrs=None, number_attrs=None, options=()): widgets = [ forms.Select(choices=options, attrs=attrs if series_attrs is None else series_attrs), forms.TextInput(attrs=attrs if number_attrs is None else number_attrs) ] super().__init__(widgets) def decompress(self, value): if value: return [value[:2], value[2:]] return [None, None] #MyForm class MainForm(forms.Form): SERIES_CHOICES = [('ХА', 'ХА')] sic = SICField('^\\d{8}$', label='User Identity Card', widget=SICWidget(number_attrs={'placeholder': _('8-digit number of your card')}, options=SERIES_CHOICES)) The main problem is there isn't any value for the … -
Access S3 credentials from settings.py in views.py Django
I am trying to upload files to S3 bucket from views.py using following code from django.conf import settings s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\ aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY) s3.meta.client.upload_file(filename,settings.AWS_STORAGE_BUCKET_NAME,filename) But I am getting the following error An error occurred (InvalidAccessKeyId) when calling the PutObject operation: The AWS Access Key Id you provided does not exist in our records. But when I used these credentials directly, instead of importing from settings.py, I did not get any error. The reason why I don't want to use directly because I am calling them from .env in settings.py -
Django Rest Framework: Access to passed arguments from views in serializers
Before asking this question, I have seen the following links but they don't help me at all: pass extra arguments to serializer pass request context to serializer from viewset pass context from one serializer to another I have an author model that has foreign key to default django user model: apps/author/models.py class Author(models.Model): user = models.OneToOneField( User, related_name='author', on_delete=models.CASCADE, default="", ) is_author = models.BooleanField( default=True, ) full_name = models.CharField( max_length=100, default="", ) def __str__(self): return self.user.username Post model has a foreign key to Author. apps/posts/models.py class Post(models.Model): author = models.ForeignKey( Author, related_name="posts", on_delete=models.CASCADE, ) title = models.TextField( null=True, blank=True, ) content = models.TextField( null=True, blank=True, ) is_draft = models.BooleanField( default=True ) created_at = models.DateTimeField( auto_now_add=True, null=True, ) published_at = models.DateField( null=True, blank=True, default=None, ) def __str__(self): return str(self.id) + ", " + self.title Problem Definition: In order to create a new post, I am getting the current user from self.request.user in views, and pass it to the PostSerializer. But whenever I want to create a new post using the following request to localhost:8000/posts/ I have got an error: # I also added JWT authorization header to the postman! and it doesn't have any problem at this level { "title": "", … -
How to hide/unregister the Accounts and Social accounts created by django-allauth from django admin?
I am beginner to django and i wanted to try google authentication and when i followed the steps from here i am able to sucessfully add a google login button but it also showing the ACCOUNTS and Social Accounts in django admin. How can i hide them ? I tried unregistering them but it always giving error thats its not registerd.