Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ProgrammingError at /add-to-cart/ in Django
I'm using Django as a backend and PostgresSQL as a DB and HTML, CSS, JS as frontend. Well, I have successfully added data to Django and also in PostregsSQL with models. Well, I want to See the selected product in Cart product in Django but showing this error. What is error in below code can someone tell me? I'm getting this error ProgrammingError at /add-to-cart-5888/ column "quantity" of relation "app_cartproduct" does not exist LINE 1: ...app_cartproduct" ("cart_id", "product_id", "rate", "quantity"... models.py class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) total = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Cart: " + str(self.id) class CartProduct(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return "Cart: " + str(self.cart.id) + " CartProduct: " + str(self.id) views.py class AddToCartView(TemplateView): template_name = "status.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # get product id from requested url product_id = self.kwargs['pro_id'] # get product product_obj = Product.objects.get(id = product_id) # check if cart exists cart_id = self.request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id = cart_id) this_product_in_cart = cart_obj.cartproduct_set.filter(product = product_obj) if this_product_in_cart.exists(): cartproduct = this_product_in_cart.last() cartproduct.quantity += 1 cartproduct.save() cart_obj.save() else: cartproduct = CartProduct.objects.create(cart = cart_obj, product = product_obj, quantity = … -
Can I use a for loop to generate field names inside a django model class
Can I use a for loop to generate field names inside a django model class. Example In the below example Task will be another model class written inside the same models.py class Task(models.Model): task_name = models.Charfield(max_length=120) def __str__(self): return self.task_name class subtask(models.Model): subtask_list = tasks.objects.all() for subtask in subtask_list: subtask.task_name = models.FloatField(default=0.0, null=True, blank=True) -
Django Calculate Similar Posts Based On Categories Not Working
I want to calculate similar posts based on categories. This is what I have so far in models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default=15) def get_related_posts_by_tags(self): category = get_object_or_404(Category, name=self.category.title) posts = Post.objects.filter(category=category) return posts class Category(models.Model): name = models.CharField(max_length=250, unique=True) And in my templates: {% for posts in object.get_related_post_by_tag %} {{ posts.title }} {% endfor %} For whatever reason, this does not work, and in my template, I do not seen any posts with the same category. This is why I am wonder if I am doing it wrong, or if I have little problem I easily fix. Thanks for all help. -
Django TypeError when trying to save the model
I am trying to create a todo add but when I try to save my model it says todo got an unexpected keyword argument . TypeError at / todo() got an unexpected keyword argument 'user' it throws the following error My models.py class todo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() date= models.DateTimeField(auto_now = True) is_completed = models.BooleanField(default=False) def __str__(self): return self.user.username + self.title And my views looks like this def todo(request): if request.method == "POST": title = request.POST.get('title') description = request.POST.get('description') todo_list = todo(user=request.user, title=title, description= description) todo_list.save() messages.success(request, 'Successfully Created') return render(request, 'main/todo.html') Please help me out -
Django submit form in bootstrap modal
i know that there are a lot of posts with similar topic as this one, but none of them seem to be a useful fix in my case at least. As the headline describes i want to be able to send a new comment form to my database from a bootstrap modal. My data is being shown just fine so the only problem i got is that when i fill out the data for a new comment and press the submit button the modal is just being dismissed and no action has happened in my DB. My best guess for why it is not working is because i got my modal data in a separated html file detail.html. But otherwise i was not able to display the right data for each posts. button to open the modal in home.html: <a class="btn btn-outline-primary post_details-btn" class="open-modal" data-url="{% url 'post_detail' post.pk %}" width="17" height="17"><i class="fa fa-comments"></i></a> my modal in home.html where i display the data from detail.html in the div with the id = modal-div <div class="modal fade" id="myModal2"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">WINNER:</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div id="modal-div"></div> </div> </div> </div> </div> my … -
Using a single index for multiple arrays in a single for loop
I'm working on a django project which takes multiple arrays from the view and shows it on a datatable. I can use loop to print a single element properly but can't for the other arrays. Is there any workaround for this issue? The code sample is given below: <tr> <td> {{x}} </td> <td> <a href="{{link|safe}}">link text</a> </td> <td> {{time|safe}} </td> <td> {{uploadername|safe}} </td> </tr> {% endfor %} In the given picture I want the other column elements to show properly like the first column. Is there any workaround for this? -
How to collect Data from a Website using Django?
I'm currently working on a project where I have a website that should give me information from various Github projects (username, projectname, ...). However, I don't know exactly how to read this data out of the Githubpage. The project is carried out using Django. Is there any way to get the information out with iframes or an API? I've done some research now but haven't come across anything useful. Thank you for your help! -
The view videos.views.add_comment_post didn't return an HttpResponse object. with the second object in Django
I try to build a blog and this blog consist of posts and these posts have comments, When I add comment to the first post it adds succussfuly but when I try to add comment the second or third this error raise ValueError: The view videos.views.add_comment_post didn't return an HttpResponse object. It returned None instead. and I tried to add comment form to the template without any widgets commentForm = PostCommentForm() to the template {{commentForm }} and I filled it and this proplem still My Post model class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) article = models.TextField(null=True, blank=True) photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath) created_date = models.DateTimeField(auto_now_add=True) class PostCommentIDF(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() publish = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) My create comments view comment_form = PostCommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.save() result = comment_form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result': result, 'user': user}) My comments Form class PostCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = PostCommentIDF fields = {'post', 'content'} widgets = { 'content': forms.Textarea(attrs={'class': ' form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True', }) } def save(self, *args, **kwargs): PostCommentIDF.objects.rebuild() return super(PostCommentForm, … -
NotImplementedError: PostCreateView is missing the implementation of the test_func() method
Please help me solve this bug Iam in learning stage in django and here's my code: views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.http import HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post # Create your views here. def home(request): context = { 'posts' : Post.objects.all } return render(request,'blog/home.html',context) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] # <app>/<model><viewtype>.html class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin, UserPassesTestMixin,CreateView): model = Post fields = ['title','content'] class PostUpdateView(LoginRequiredMixin,UpdateView): model = Post fields = ['title','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin,CreateView): #LoginRequiredMixin, UserPassesTestMixin,DeleteView #LoginRequiredMixin, AuthorMixin, ListView model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False def about(request): return render(request,'blog/about.html',{'title':'About'}) error : NotImplementedError: PostCreateView is missing the implementation of the test_func() method. Iam learning to code in django and Iam facing frequent bugs please help me Iam trying to do this with my full energy and Iam a self taught coder so I have no one to ask my questions or … -
Django Forms - How to make certain fields readonly except for superuser
I use UserChangeForm and UpdateView, to update user information the UpdateView is only accessible for the owner of the account and superuser. now, I need to make the username and subject fields to be read only when the owner wants to edit their profile info but it will be editable when superuser access wants to edit it. forms.py class TeacherUpdateForm(UserChangeForm): class Meta: model = Profile fields = ["username", "first_name", "last_name", "email", "phonenumber", "address", "subject"] views.py class TeacherUpdateView(UpdateView): model = Profile form_class = TeacherUpdateForm template_name = "account/update_form.html" def get_context_data(self, **kwargs): kwargs["user_type"] = "Teacher" return super().get_context_data(**kwargs) def get_object(self, *args, **kwargs): obj = super(TeacherUpdateView, self).get_object(*args, **kwargs) if obj.id is self.request.user.id or self.request.user.is_superuser: return obj else: raise PermissionDenied() def form_valid(self, form): form.save() return redirect(reverse("index")) I feel stuck because every solution I see is using get_readonly_fields and it doesn't work on the forms or views. For another info, the subject field is a foreignkey from another model. -
How to combine multiple querysets in django
Suppose there is an event model and for each event there is one client and one consultant. Also, one consultant can have multiple events. Each event has number of different documents. I am trying to display list of events when a consultant logs in and in that list od events it should display their respective documents. Models.py: class Client_Profile(models.Model): user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # Field name made lowercase. first_name = models.CharField(db_column='First_name', max_length=50) # Field name made lowercase. last_name = models.CharField(db_column='Last_name', max_length=50) # Field name made lowercase. phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10) # Field name made lowercase. # role_id = models.ForeignKey(Role, on_delete=models.CASCADE) def __str__(self): return self.first_name class Consultant_Profile(models.Model): user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # Field name made lowercase. first_name = models.CharField(db_column='First_name', max_length=50) # Field name made lowercase. last_name = models.CharField(db_column='Last_name', max_length=50) # Field name made lowercase. phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10) # Field name made lowercase. # role_id = models.ForeignKey(Role, on_delete=models.CASCADE) def __str__(self): return self.first_name class Event(models.Model): event_id = models.AutoField(db_column='event_id', primary_key=True) client_id = models.ForeignKey(Client_Profile, db_column='Client_ID', on_delete=models.CASCADE) # Field name made lowercase. consultant_id = models.ForeignKey(Consultant_Profile, db_column='Consultant_ID', on_delete=models.CASCADE) # Field name made lowercase. def __str__(self): return str(self.event_id) class Document(models.Model): document_id = models.AutoField(db_column='document_id', primary_key=True) document_name = models.CharField(db_column='document_name', max_length=50, null=True, blank=True) # Field name made lowercase. … -
Is select_related() still needed after defining only() in django query
select_related is used so whenever a defined foreign key accessed, it will be included in the first query and won't issue another query to db. But I have a case when only few fields are needed. Here is the example class PMapKomoditi(models.Model): id = models.IntegerField(primary_key=True) komoditi_fk = models.ForeignKey(PMastKomoditi, models.RESTRICT, db_column='id_komoditi') kd_komoditi = models.CharField(max_length=2) nm_komoditi = models.CharField(max_length=50, blank=True, null=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) // ... class PMastKomoditi(models.Model): id = models.AutoField(primary_key=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) // ... I only need kd_komoditi & komoditi_fk properties, so I do query the following: my_query = PMapKomoditi.objects.select_related( 'komoditi_fk' ).Only( 'kd_komoditi', 'komoditi_fk' ) Do I need to include the select_related or it's already covered with only()? -
I am getting type error white i'm fetching orders from logged in user . how i can solve it?
Error screenshot https://drive.google.com/file/d/1IBhNsKHGXc2SQNp4q4Q_N3k9LwOi50MO/view?usp=sharing views.py def orders(request): customer = request.session.get('id') print(type(customer)) get_order = Order.get_order_by_id(customer) print(type(get_order)) return render(request , "orders.html" , {'ord':get_order} ) model from django.db import models from .customer import Customer from .product import Product import datetime class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) address = models.CharField(max_length = 100 ) phone = models.CharField(max_length = 20) price = models.IntegerField(default=0) date = models.DateField( default=datetime.datetime.today) def __str__(self): return self.product.p_name + " - " + self.customer.firstname @staticmethod def get_order_by_id(customer_id): return Order.objects.filter(customer = customer_id) -
need of postgraphile with django backend
My app is in frontend react-native and backend in django using graphene (for graphql apis), database is postgresql. Do i need postgraphile or hasura with it or let the django do the work? i m new to backend development , any help would be appreciated Thanks -
How can I use Django and React-js with AWS s3 bucket?
I am trying link my Django App (coupled with React-Js App) with my s3 bucket but despite the everything I have tried, something is still not working right. First, below is my settings.py; import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get("APP_SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = (os.environ.get("APP_DEBUG") == "True") DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'account', 'products', 'orders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #installed apps 'rest_framework', 'corsheaders', 'storages', ] AUTH_USER_MODEL = 'account.User' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "build", ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Database import dj_database_url if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } else: DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) #S3 bucket SETTINGS if not DEBUG: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_URL = os.environ.get('AWS_URL') AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'eu-west-2' AWS_S3_SIGNATURE_VERSION = 's3v4' if DEBUG: STATICFILES_DIRS = [ BASE_DIR / "build/static", #removing this makes my app not to show up … -
Like text to icons or svg image and claps like medium implementation on my post like
**how can i use icon for like ** Is there a method to include claps like medium for my like post how to implement Clap html file for like post <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="" data-id="{{ post.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} Like {% else %} Unlike {% endif %} </a> ajax script to like $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "blog:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); //toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); //toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); //update total likes var previous_likes = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } }); }); -
Django Template Round to Nearest Non Zero
Problem: Rounding variable size input to variable lengths based on the trailing decimals. Description: I am building a recipe app for cocktails meaning I want to have some variability with storing measurements in ml at varying lengths. Let's say I have a recipe consisting of: 50ml Gin 25ml Lime Juice 12.5ml Simple Syrup 1.25ml Maraschino Liqueur (This is just an example recipe - it's gonna taste like sour piss - don't bother making it) This is currently stored in this model: class Ingredients(models.Model): SLU = ForeignKey("Spec", on_delete=CASCADE) PLU = ForeignKey("Product", on_delete=CASCADE) measure = models.DecimalField(decimal_places=3, max_digits=5) This means the values in storage are: 50.000 Gin 25.000 Lemon Juice 12.500 Simple Syrup 1.250 Maraschino Liqueur How do I best get these values displayed to the user with no trailing zeroes in the same way as originally displayed above when first showing the recipe? Solutions Using Django's |floatformat does not solve the problem as it displays as follows: floatformat:"2": 50.00, 25.00, 12.50, 1.25 floatformat:"-2": 50, 25, 12.50, 1.25 Using a regular Math rounding function in python backend will cause similar results as above unless I make it longer with hard coded options for all 3 possible decimals. Any good suggestions for this? -
Field 'id' expected a number but got 'A1'
When I visit http://localhost:8000/details/A1/ I get this error “Field 'id' expected a number but got 'A1'”. What am I doing wrong? models.py class Chips(models.Model): id = models.AutoField(primary_key=True) brand = models.CharField(max_length=300) cost = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return "{}: {}, {}".format( str(self.pk), self.brand, self.cost, ) views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import * def details(request, pk): w = get_object_or_404(Chips, pk=pk) return render(request, 'MyApp/details.html', {'w': w}) urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('details/<pk>/', views.details, name='details'), ] -
How to get BSSID of Access Point from client?
I am developing a Django application and I need to know to which access point the client/user is connected to. By searching in the internet I found out that I can find it using the BSSID of the access point. The problem is I am unable to find a way to get that BSSID. So, I want to know is there any information in the request object of Django. If not, is there any other way to get the BSSID using JavaScript. (Note: Please share any way that can be helpful to me). If all those can't work can we set some configurations in the access point and use them to find the client access point (Yes, I have the option to set them as we are developing this application to be run on a organization server). Any information will be appreciated. Thank you in advance. -
get() got an unexpected keyword argument 'pk_news'
views.py: class NewsCommentsUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comment fields = ('comment',) template_name = 'news/comment_edit.html' def get_absolute_url(self): return reverse_lazy('news_detail', args=[str(self.object.news.id)]) def get(self, request): return Comment.objects.get(pk_news=self.request.GET.get('news_id'), pk=self.request.GET.get('id')) def test_func(self): obj = self.get_object() if self.request.user.has_perm('news.all') or self.request.user.has_perm('news.delete_news') or obj.author == self.request.user: return True urls.py: path('<int:pk_news>/comment_edit/<int:pk>/', NewsCommentsUpdateView.as_view(), name='comment_edit'), path('<int:pk_news>/comment-delete/<int:pk>/', NewsCommentsDeleteView.as_view(), name='comment_delete'), template: {% for comment in object.comments.all %} <a href="{% url 'comment_edit' pk_news=news.pk pk=comment.pk %}">Edit</a> | <a href="{% url 'comment_delete' pk_news=news.pk pk=comment.pk %}">Delete</a> {% endfor %} It does not work and gives me an error (get() got an unexpected keyword argument 'pk_news'). -
look up the value in jsonfield of django
The model contains a jsonfield: class MyModel(Model): test_result = JSONField() the data to be handled is dynamic, {'test1':100,'test2':95,'test9':80,...} , { 'test2':60, 'test3':80,'test6':70,... } ... I want to find all the test results of 'test2' and save them into a list. all_score_of_test2 =[x.test_result['test2'] for x in MyModel.objects.filter(test_result__has_keys=['test2'])] it works but the performance is not good. Is there any faster way to do the task? I am using postgresql13.1 -
Django - 'Paginator' object has no attribute 'get_page'
I am trying to use paginator for the first time on my django. I am having problems getting it to work. When i run it I get the error AttributeError: 'Paginator' object has no attribute 'get_page'. I cannot seem to resolve it. Can somebody help me please? The error seems to be o the line def index(request): page = request.GET.get('page', '1') posts = BoardTbl.objects.raw( # ORM 미사용 'SELECT b.idx, u.last_name, u.first_name, b.subject, b.content, b.date ' 'FROM board_tbl b ' 'JOIN auth_user u ' 'ON b.writer = u.id' ) paginator = Paginator(posts, 15) page_obj = paginator.get_page(page) #count = len(list(posts)); context = {'posts': page_obj} # return render(request, 'post/index.html', {'posts':posts, 'count':count}) return render(request, 'post/index.html', context) -
Why does my Environ import doesn't import .env variables?
I'm building a Django app but I've got an issue... I've imported the environ package in order to store all my variables in a .env file, but actually it seems my app doesn't read it and I can't get why. Here is my .env file: DEBUG=True SECRET_KEY='9l=jjp#g0-mbdfsntqww91&s9b^a!kj44ljl4f5h!+uoft$h6u' DB_NAME=djcrm DB_USER=djcrmuser DB_PASSWORD=djcrm123 DB_HOST=localhost DB_PORT= EMAIL_HOST= EMAIL_HOST_USER= EMAIL_HOST_PASSWORD= EMAIL_PORT= DEFAULT_FROM_EMAIL=davide@davidemancuso.com Here is my settings.py file: from pathlib import Path import environ env = environ.Env( DEBUG=(bool, False) ) READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False) if READ_DOT_ENV_FILE: environ.Env.read_env() DEBUG = env('DEBUG') SECRET_KEY = env('SECRET_KEY') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third party apps 'crispy_forms', 'crispy_tailwind', 'tailwind', 'theme', # Local apps 'leads', 'agents', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djcrm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates" ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djcrm.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("DB_NAME"), 'USER': env("DB_USER"), 'PASSWORD': env("DB_PASSWORD"), 'HOST': env("DB_HOST"), 'PORT': env("DB_PORT"), } } # Password … -
Pass query params but got error that query params is required
I write some unit tests for my django app. but test failed, because of that query params missed but I passed the quarry params. this is one of my tests: def test_delete_card(self): url = reverse("postideas-urls:DeleteCard") card_pk=self.test_card_second.id data3 = { 'card_pk':card_pk } self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token) response = self.client.delete(url,params=data3) print(response.__dict__) self.assertEqual(response.status_code, status.HTTP_200_OK) and this is my response.__dict___ ... '_container': [b'{"error":"card_pk query param(s) are required"}'], '_is_rendered': True, 'data': {'error': 'card_pk query param(s) are required'}, 'exception': False, 'content_type': None, 'accepted_renderer': <rest_framework.renderers.JSONRenderer object at 0x7fb757f3aad0>, 'accepted_media_type': 'application/json', 'renderer_context': {'view': <postideas.views.DeleteCardView object at 0x7fb757f37d10>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request: DELETE '/api/v1/postideas/Delete_Card/'>, 'response': <Response status_code=400, ...'request': {'PATH_INFO': '/api/v1/postideas/Delete_Card/', 'REQUEST_METHOD': 'DELETE', 'SERVER_PORT': '80', 'wsgi.url_scheme': 'http', 'params': {'card_pk': 5}, 'QUERY_STRING': '', 'HTTP_AUTHORIZATION': 'Bearer ... -
Want to edit filename in django form
from django.shortcuts import render, redirect, reverse from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required from .forms import UploadFileForm, EditFileName from .models import Image @login_required def home(request): context = {} if request.method == "PUT": print(request.FILES) form2 = EditFileName(request, request.FILES) if form2.is_valid(): username = request.user image = request.FILES["image"] image_text = form2.cleaned_data.get("image") obj = Image.objects.filter(id = ).update( image_text = image_text ) else: form2 = EditFileName() if request.method == "POST": print(request.user) form = UploadFileForm(request.POST, request.FILES) print(request.FILES) if form.is_valid(): username = request.user image_text = request.FILES["image"].name image = form.cleaned_data.get("image") obj = Image.objects.create( username=username, image_text=image_text, image=image ) obj.save() print(obj) else: form = UploadFileForm() context['form'] = form context['data'] = Image.objects.all() context['form2'] = form2 print(context) return render(request, "registration/success.html", context) def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form': form}) this is my views.py, i want to use form2 to edit the filename of the image that i uploaded in form. from django import forms from django.contrib.auth.models import User from django.forms.fields import CharField class UploadFileForm(forms.Form): image = forms.ImageField() class EditFileName(forms.Form): filename = CharField(max_length=200) this is my forms.py. I just want …