Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django test fails with 'django.db.utils.ProgrammingError: relation "django_content_type" does not exist'
I'm trying to write and run tests for a Django project, but running $ python manage.py test apps/actions/tests gives the following error: django.db.utils.ProgrammingError: relation "django_content_type" does not exist This only happens when I try to run the tests. Running python manage.py runserver gives me no error whatsoever and everything works fine. Here's the full traceback: Traceback (most recent call last): File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Kamil\Projekty\fast-intercept\manage.py", line 22, in <module> main() File "C:\Users\Kamil\Projekty\fast-intercept\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv super().run_from_argv(argv) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\commands\test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\test\runner.py", line 695, in run_tests old_config = self.setup_databases(aliases=databases) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\test\runner.py", line 614, in setup_databases return _setup_databases( File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\test\utils.py", line 170, in setup_databases connection.creation.create_test_db( File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\db\backends\base\creation.py", line 72, in create_test_db call_command( File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output … -
Update the 'CHOICE' in the post method
I have a Model with Choices applied to one of the attributes: class Booking(models.Model): BOOKING_STATUS_CHOICES = [ ('RESERVED', 'Reserved'), ('COMPLETE', 'Complete'), ] status = models.CharField( max_length=10, null=False, blank=False, choices=BOOKING_STATUS_CHOICES, default='RESERVED' ) other_attributes = models.OtherFields() etc My ModelForm does not include this attribute as a form field. Instead, I want to update the value in the post method of the form. I am loosely following a walkthrough project where the form is saved but not committed, and then any other values that werent part of the form are added to the form instance before committing the save. What I have is below: def post(self, request): form = self.form_class(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.status = "COMPLETE" booking.save() However checking the admin panel afterwards shows this value has not been applied. I am sure this is really simple to do but I can't find how to do it. Any help would be appreciated -
fatal: Out of memory, malloc failed (tried to allocate 524288000 bytes)
I am working with django. I have first tracked the staticfiles folder which is generated when we run python manage.py collectstatic {'its a copy of original static files actually"}. I don't want to track it because its increasing size of project while deploying and push in git. so i just added it in gitignore and removed from index using 'git rm -r --cached foldername'. After it when i try to push changes its giving error. Previously i have modified my config files to push larger files. Error: fatal: Out of memory, malloc failed (tried to allocate 524288000 bytes) I thing My config file: [core] repositoryformatversion = 0 filemode = false bare = false logallrefupdates = true symlinks = false ignorecase = true packedGitLimit = 128m packedGitWindowSize = 128m [remote "origin"] url = 'removed for privacy ' fetch = +refs/heads/*:refs/remotes/origin/* [branch "master"] remote = origin merge = refs/heads/master [branch "developer"] remote = origin merge = refs/heads/developer [remote "heroku"] url = 'removed for privacy ' fetch = +refs/heads/*:refs/remotes/heroku/* [pack] deltaCacheSize = 128m packSizeLimit = 128m windowMemory = 128m -
Seperation of dialogues based on specific users in Django
I am trying to implement direct messaging into my blog app using Django. Pretty much like Instagram direct but without using anything fancy like socket programming and Django channels. In other words, I don’t want online and instant chatting. I have made a simple Message in my message app in my project. It works properly and users can send messages to each other. The problem is that when I want to bundle each dialogue (two specific user) I cannot do it. I mean, I get all messages pretty fine but I cannot find any way to separate messages between different users. I want user to be able to click on the person that he or she wants and after that in a separate url his or her messages will be shown. I know that I have not included any code and my problem is so abstract. But to be honest my problem is the methodology of implementing this not the Django code itself. -
make a write_only field conditionally required in django rest framework
I have a field in my serializer which is required conditional on value of another field. say password is required only if registerField is email. I have this serializer class UserSerializer(ModelSerializer): ... password = CharField(write_only=True, required=False) def validate(self, data): if 'email' in data.keys() and 'password' not in data.keys(): raise ValidationError({'password', 'this field is required'}) return data this method works, but the response is: { "non_field_errors": [ "{'this filed is required', 'password'}" ] } but I want it to be like { "password":"this filed is required" } -
post() got an unexpected keyword argument 'id'
Hello i am trying to create quantity plus button where I can add 1 quantity per click but whenever I click the plus button i got this error.i don't know why I am getting this kind of error.Please also explain why I am getting this error and also please give me solution : post() got an unexpected keyword argument 'id' Here is my cart.py: @register.filter(name='in_cart') def in_cart(product, cart): keys = cart.keys() for id in keys: if int(id) == product.id: return True return False @register.filter(name='cart_quantity') def cart_quantity(product, cart): keys = cart.keys() quantity = 0 for i in keys: if int(i) == product.id: quantity = cart.get(i) else: continue return quantity Here is my Views.py: def post(self, request): product = request.POST.get('product') cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = cart.get(product) if quantity: if remove: cart[product] = quantity - 1 else: cart[product] = quantity + 1 else: cart[product] = 1 if cart[product] < 1: cart.pop(product) else: cart = {} cart[product] = 1 request.session['cart'] = cart return redirect('product_details') Here is my index.html: where I want to apply this functionality: <div>{{products|cart_quantity:request.session.cart}} in cart</div> <form acrtion="/" method="POST"> {% csrf_token %} <input type="text" name="product" value="{{products.id}}" /> <input type="submit" value="+" /> </form> -
This site can't be reached, docker-compose up does not show any error
this is the following up question from my last question to learn and deploy React and Django with Nginx and Docker while following Piotr's answer (link). I'm at the stage of deploying the development docker-compose without any SSL certificate. I have changed the code from Piotr's answer (link included above) to fit with my project name and directory, but after running ``docker-compose -f ... up` without any error, the site is showing This site can’t be reached. I'm still new to docker and Nginx and would really appreciate any guidance or troubleshooting tips on this issue. I have attached here: docker-compose-dev.yml, Dockerfile for Nginx and backend; my project directory tree; docker log; Nginx default.conf; wsgi-entrypoint.sh. Thank you!!! project directories: . ├── docker │ ├── backend │ │ ├── Dockerfile │ │ └── wsgi-entrypoint.sh │ └── nginx │ ├── Dockerfile │ └── development │ └── default.conf ├── docker-compose-dev.yml ├── front-end │ ├── README.md │ ├── debug.log │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── src │ └── yarn.lock ├── housing_dashboard_project │ └── housing_dashboard │ ├── dashboard_app │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ ├── models.py │ │ ├── serializers.py │ │ … -
Error when using Angular to upload image to Django REST API
I created a Django REST framework API to upload data and images. When I using the REST API website, I can upload images properly. However, when I try to use Angular to create a frontend to upload images, it raise an error in console. The full error page is shown as below Here is my codes in Angular: .ts: public registrationForm: FormGroup; ngOnInit() { this.apiService.getLearnid(this.id).subscribe( (data) => this.learn = data, (error) => this.errorMsg = error, () => console.log('the sequence completed!') ); this.registrationForm = this.fb.group({ name: ['',], learn_type: ['',], createtime: ['',], status : ['',], problems: ['',], image: ['',], }); } fileChange(event) { let fileList: FileList = event.target.files; let file: File = fileList[0]; this.registrationForm.value.image = file } onSubmit() { console.log(this.registrationForm); console.log(this.registrationForm.value); //console.log(this.registrationForm.value.userName); //console.log(this.registrationForm.value.password); //--test //--endtest this.id = parseInt(this.route.snapshot.paramMap.get('id'));; this.apiService.editLearn(this.id,this.registrationForm.value) .subscribe( response => console.log('Success!', response), error => console.error('Error!', error) ); //window.location.reload() } .html: <form [formGroup]="registrationForm" (ngSubmit)="onSubmit()" enctype='multipart/form-data'> <div class="form-group"> <label>Name</label> <input type="text" formControlName="name" class="form-control" [(ngModel)]="learn.name"><br> <label>Learning Type</label> <select formControlName="learn_type" [(ngModel)]="learn.learn_type"> <option value="study material"> study material </option> <option value="test problems"> test problems </option> <option value="exam"> exam </option> </select> <label>Create Time</label> <input type="datetime" formControlName="createtime" [(ngModel)]="learn.createtime" class="form-control"><br> <label>Image</label> <input type="file" formControlName="image" (change)="fileChange($event)" class="form-control" ><br> <label>status</label> <input type="json" formControlName="status" [(ngModel)]="learn.status" class="form-control"><br> <label>problems</label> <input type="json" formControlName="problems" [(ngModel)]="learn.problems" class="form-control"><br></div> … -
When I include GroupedForeignKey, ChainedForeignKey to my project the web servers(Apache, and IIS) give errors(500 - Internal server error.)
I used Django-smart-select to my project, before including the smart-select to model.py everything work properly but when I import GroupedForeignKey, ChainedForeignKey from Django-smart-select (from smart_selects.db_fields import GroupedForeignKey, ChainedForeignKey) the web servers(IIS, Apache) give errors. Apache errors (500 internal server error) IIS errors (Traceback (most recent call last): File "c:\python37\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\python37\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\python37\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = import(module_name, fromlist=[name_list[0][0]]) File "C:\inetpub\wwwroot\webproject\webproject\wsgi.py", line 16, in application = get_wsgi_application() File "c:\python37\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "c:\python37\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\python37\lib\site-packages\django\apps\registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant StdOut: StdErr: ) would you please help me thank you. -
AttributeError at /checkout/ 'QuerySet' object has no attribute 'id'. can't access to my automactically created 'id model
I'm a beginner at django. It's my first time to post there. That's why feel free to point if I have done something wrong. I'm doing 'e-commerce page' project. I'm using django 3.1.3. I can't get access to my 'id' model in my Order model: from django.db import models from django.contrib.auth import get_user_model # Create your models here. from products.models import Product User = get_user_model() ORDER_STATUS_CHOICES = ( ('created', 'Created'), ('stale', 'Stale'), ('paid', 'Paid'), ('shipped', 'Shipped'), ('refunded', 'Refunded'), ) class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=20, choices=ORDER_STATUS_CHOICES, default='created') sub_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) tax = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) paid = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) shipping_address = models.TextField(blank=True, null=True) billing_adress = models.TextField(blank=True, null=True) timestamp = models.DateField(auto_now=True) This is my view: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required # Create your views here. from .models import Order from products.models import Product @login_required def checkout_order(request): qs = Product.objects.filter(featured=True) if not qs.exists(): return redirect('/') product = qs.first() user = request.user # without login_required there will be AnonUsers so we don't want it order_id = request.session.get('order_id') order_obj = None try: order_obj = Order.objects.filter(id=order_id) except: order_id = … -
get chained queryset ajax django
I want to get a queryset through ajax request and use it as I can do with django queryset in template. I have the following codes: # view.py def ajax_get_allocates_by_date(request): """ ajax 요청 함수 """ today = timezone.localdate() date = request.GET.get('kw', today.strftime('%Y-%m-%d')) date=parse_date(date) d=Date.objects.get(date=date) allocate_list = Allocate.objects.filter(date=d) data = { 'date': serializers.serialize( 'json', [d] ), 'allocate_list': serializers.serialize( 'json', allocate_list ) } return JsonResponse(data) template <form method="get"> ... <input type="text" id="refer-date" name="refer-date" class="frm_input2 frm_date"> ... </form> ... <script> $('#refer-date').datepicker({ onSelect: function(dateText, inst) { let date = $(this).val() console.log(date) $.ajax({ url: "{% url 'allocate:get-allocates-by-date' %}", data: { 'kw': date }, success: function(data) { let date = JSON.parse(data.date) let queryset = JSON.parse(data.allocate_list) console.log(date) console.log(queryset) } }) } }) </script> If the value of #refer-date is changed, I get ajax response and it is logged in console. However, my Allocate model has some other ForeignKey relationship, which I also want to display in the template. For now it seems I can only render some id if the field is ForeignKey. The best would be use django for loop as ajax response, but I'm not sure how I can achieve that. Any suggestion would be highly appreciated. Thank you. -
Comment is not adding after click on add 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',) Please help me in this. I will really appreciate your Help. -
Django ValueError: Field 'id' expected a number but got 'myuser'
I need to use my usernames to panel/profile/<username> address. So what I did in models is: class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) def __str__(self): return str(self.user) And in urls.py I have these paths: urlpatterns = [ path('panel', views.home, name='panel'), path('panel/register', views.registerPage, name='register'), path('panel/login', views.loginPage, name='login'), path('panel/logout', views.logoutPage, name='logout'), path('dashboard', views.userProfile, name='dashboard'), path('dashboard/settings/edit-profile', views.userSettings, name='settings'), path('panel/profile/<str:username>', views.profile, name='profile'), ] and in this way there is no problem: >>> customer=Customer.objects.get(user_id=118) >>> customer.user.username 'myuser' But in views.py I need to grab username as a part of URL like that: @login_required(login_url='login') @allowed_users(allowed_roles=['admins']) def profile(request, username): customer = Customer.objects.get(user=username) print(type(customer), customer) But I have this error: ValueError at /panel/profile/myuser Field 'id' expected a number but got 'myuser'. -
Callback Endpoints in Django
I have a scenario were a view function sends a post request to an external webserver which sends the callback response to a endpoint in my application. My question is how do I identify the session flow, that is how do I know that the callback response on the endpoint is for the user who triggered the view function initially. -
Django view not executing
I'm implementing an excel export function in one of my django apps, but when I click the link that is supposed to execute the view, nothing happens, and the server is not running the view at all. This is the button that is supposed to run that view: <li class="nav-item mt-sm-2 mt-lg-0"> <a href="{% url 'catalog:export_all_csv' %}" class="btn btn-success btn-sm" download="OrdenesProximas" tabindex="0" data-toggle="popover" data-trigger="focus" title="¡Archivo descargado!" data-content="El archivo ha sido descargado exitosamente."> <i class="uil-file"></i> Exportar catálogo a Excel </a> </li> My urls.py for the app: from django.urls import path from . import views app_name = 'catalog' urlpatterns = [ path('catalog/list/', views.ProductList.as_view(), name='product_list_table'), path('catalog/add/', views.create_product, name='add_product'), path('catalog/category/add/', views.CategoryCreate.as_view(), name='add_category'), path('catalog/<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('catalog/<slug>/list/', views.CategoryProductList.as_view(), name='category_product_list_table'), path('catalog/', views.product_list, name='product_list'), path('catalog/<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), path('catalog/<int:id>/<slug:slug>/edit/', views.edit, name='product_edit'), path('catalog/export_csv/', views.export_csv, name='export_all_csv'), ] The view: @login_required def export_csv(request): import pdb; pdb.set_trace() categories = Category.objects.filter(company=request.user.profile.company) queryset = Product.objects.filter(category__in=categories) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'filename=productos.csv' writer = csv.writer(response) writer.writerow(['Id de Producto', 'Categoría', 'Nombre del producto', 'SKU', 'Código de barras', 'Marca', 'Proveedor', 'Color', 'Medidas', 'Descripción', 'Observaciones', 'Precio 1', 'Precio 2', 'Precio 3', 'Impuesto (%)', 'Costo de fabricación']) for item in queryset: writer.writerow([item.id, item.category.name, item.name, item.sku, item.barcode, item.brand, item.provider, item.color, item.measures, item.description, item.observations, item.price_1, item.price_2, item.price_3, item.tax, item.fabrication_cost]) return response …