Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't open django admin from my live website in cPanel [too many redirects]
I am trying to open https://mywebsite.org/admin but it's responsing "This page isn’t working, mywebsite.org redirected you too many times. Try deleting your cookies. ERR_TOO_MANY_REDIRECTS." everything is working perfect in my local server. I'm facing this only on the live server in cPanel. All other tasks are working fine without the admin page. I am stuck for last 2 days on the same issue. I have tried most of the solutions available online . ensured static files transfered collect_static's admin folder to the public_html folder of cPanel checked all my urls used ADMIN_MEDIA_PREFIX = '/static/admin/' in the settings.py used whitenoise I am using deafult sqlite3 database of django. is that the issue? -
make sure that requests to my server come from my site and as a result of user interaction with it
I made a small react app that sends the following request to my server: const formData = new FormData(); formData.append('file', pdfFileSelected); formData.append('password', pdfPassword.current); formData.append('selected_pages', selectedPages); formData.append('save_separate', saveSeparate.current.checked) fetch('https://mydomain/pdf-processing/split/', { method: 'POST', body: formData }).then(response => response.json()) .then(data => console.log(data)); I have the server part on Django. But the problem is that someone can programmatically send such requests to my server. I know about the origin header in requests, but it can be modified in CLI scripts. I also tried the csrf token, but you can take it from the cookies of your browser and insert it into the form in your script. Are there any methods to verify that the request came from my domain and as a result of user interaction with the site? And if there are no such countermeasures to limit third-party requests to my server, then is it possible to simply limit the number of requests per day by IP? -
Programmatically create more workers at run-time by using Django_rq
I want to increase the number of workers in Django project by using Django_rq(Redis Queue) the problem is that I have to manually start each worker to complete the process in short time is their any way I can increase the number of workers or their number of process at the run time by using Django_rq? The problem is that queue which has large data takes time more even after optimization of code and cannot allow the other ids to processed until its queue with large data complete . It puts other ids in queue until large queue with data is completed. -
Nâng mũi cấu trúc bao lâu thì đẹp
Thường thường, quá trình ổn định và lên form đẹp của mũi sau phẫu thuật nâng mũi mất khoảng 1-3 tháng. Tuy nhiên, do nhiều yếu tố khác nhau, có những trường hợp mà việc đạt được đường nét dáng mũi mong muốn có thể kéo dài từ 3-6 tháng. Không có thời gian cụ thể để xác định khi nào mũi sẽ đạt đến hình dạng tự nhiên và đẹp mắt sau khi thực hiện phẫu thuật nâng mũi. Sau khi thực hiện phẫu thuật nâng mũi, thời gian cần để đạt được kết quả đẹp là một điều mà những người quan tâm đến thẩm mỹ mũi thường đặt ra. Tuy nhiên, để có cái nhìn toàn diện về vấn đề này, chúng ta cần hiểu rõ về các yếu tố liên quan và tác động trực tiếp lên quá trình hồi phục trước, trong và sau phẫu thuật. -
Django admin save_model
i'm new to django, please help me in below scenoria, when i save the order inn admin panel the same_model function not working the order is saving with out a function. The requirement is when i add order in admin panel when the quantity of orderedproduct is graeter the actual quantity it should through an error else it should reduce the ordered quantity from the product. The order is working but save_model function is not working admin.py from django.contrib import admin from django.contrib import messages from django.utils.translation import ngettext from .models import Category, Product, Order, OrderItem from django.utils.html import format_html class OrderItemInline(admin.TabularInline): model = OrderItem extra = 1 class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemInline] list_display = ('id', 'user', 'order_date') def save_model(self, request, obj, form, change): errors = [] super().save_model(request, obj, form, change) for order_item in obj.orderitem_set.all(): print(order_item.quantity) if order_item.quantity > order_item.product.quantity: errors.append( f"Order quantity ({order_item.quantity}) for {order_item.product.name} exceeds available quantity ({order_item.product.quantity})." ) else: order_item.product.quantity -= order_item.quantity order_item.product.save() if errors: # If there are errors, display a message and rollback the order creation message = ngettext( "The order was not saved due to the following error:", "The order was not saved due to the following errors:", len(errors), ) messages.error(request, f"{message} {', '.join(errors)}") … -
Manager isn't accessible via object instances on object.save()
I have the following model definition in models.py: from django.db import models # Create your models here. # this is the model for each user class UTJUser(models.Model): full_name = models.CharField(max_length=80, default=None) email = models.EmailField(default=None) password = models.CharField(max_length=200, default=None) verified = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=True) last_submission = models.DateTimeField(auto_now=True) def __str__(self): return self.full_name I have the following signup function definition in views.py: from django.http import HttpResponse # for development purpose exempt csrf protection from django.views.decorators.csrf import csrf_exempt from users.models import UTJUser # sign up function, use csrf exempt for development @csrf_exempt async def sign_up(request): try: full_name, email, password = request.POST['full_name'], request.POST['email'], request.POST['password'] new_user = UTJUser(full_name=full_name,email=email,password=password) await new_user.save() return HttpResponse("Sign up success!") except: return HttpResponse.status_code However, when I run the line new_user = UTJUser(full_name=full_name,email=email,password=password) an error occur in the objects attribute of new_user: 'Traceback (most recent call last):\n File "c:\Users\micha\.vscode\extensions\ms-python.python-2023.22.1\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_resolver.py", line 189, in _get_py_dictionary\n attr = getattr(var, name)\n ^^^^^^^^^^^^^^^^^^\n File "c:\Users\micha\Documents\UTJ\backend\UTJEnv\Lib\site-packages\django\db\models\manager.py", line 186, in get\n raise AttributeError(\nAttributeError: Manager isn't accessible via UTJUser instances\n' And the final error that is returned is: Traceback (most recent call last): File "c:\Users\micha\Documents\UTJ\backend\UTJEnv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\micha\Documents\UTJ\backend\UTJEnv\Lib\site-packages\django\utils\deprecation.py", line 136, in call response = self.process_response(request, response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\micha\Documents\UTJ\backend\UTJEnv\Lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response … -
Django: Login a user after a webhook event
i am making an ecommerce app giving users session based cart and allowing then to checkout and enter their email(required) there, where when stripe webhook ping about that checkout session i create that user based on his email or get them from database if it exists, and want to log them in and move to set password page, but in django i cant use login(request, user), because request arent user generated through i have the user object, how can i achieve this functionality. i am passing session key in webhook, so that i can gather the items in those cart and process and delete them after, and gets the user or create them in the webhook. -
Django run in docker with error "permission denied"
I got an error with python environment in docker when run my django project. The environment is: OS: linux Docker: 18.09.0 Docker base images: python3:latest Command: python3 manage.py runserver 0.0.0.0:8080 error log as below: eb-1 | Operations to perform: web-1 | Apply all migrations: AlarmTransServer, admin, auth, contenttypes, sessions web-1 | Running migrations: web-1 | No migrations to apply. web-1 | Current environment is dev web-1 | Traceback (most recent call last): web-1 | File "/app/AlarmTransServer/manage.py", line 22, in <module> web-1 | main() web-1 | File "/app/AlarmTransServer/manage.py", line 18, in main web-1 | execute_from_command_line(sys.argv) web-1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line web-1 | utility.execute() web-1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/__init__.py", line 436, in execute web-1 | self.fetch_command(subcommand).run_from_argv(self.argv) web-1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/base.py", line 412, in run_from_argv web-1 | self.execute(*args, **cmd_options) web-1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 74, in execute web-1 | super().execute(*args, **options) web-1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/base.py", line 458, in execute web-1 | output = self.handle(*args, **options) web-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ web-1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 111, in handle web-1 | self.run(**options) web-1 | File "/usr/local/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 118, in run web-1 | autoreload.run_with_reloader(self.inner_run, **options) web-1 | File "/usr/local/lib/python3.12/site-packages/django/utils/autoreload.py", line 673, in run_with_reloader web-1 | exit_code = restart_with_reloader() web-1 | ^^^^^^^^^^^^^^^^^^^^^^^ web-1 | File "/usr/local/lib/python3.12/site-packages/django/utils/autoreload.py", … -
How to Design Django models with optional fields for use with ModelForm validation?
I have some models which I want to use in ModelForm. There are some optional values in the model. Since in my use-case, blank value does not make sense for those fields, thus I set null=True but not blank=True on those fields. I suppose that makes sense from a data model perspective. Problem is, when you render a ModelForm, the nullable-but-not-blankable value will have required attribute set in the HTML form. I can unroll the form and write the fields myself - but I'd rather not (because I have to create many forms). Now guess my options are: Override optional fields in ModelForm, setting required=False, but this is tedious (I have many optional fields), violates DRY and I don't want to do that. Bite the bullet and set blank=True on these models. What's the idiomatic way to use Optional fields with a ModelForm? -
Django - Cannot resolve keyword 'Customer' into field
I am trying to display an Order of an Customer in Django. I think the error is mostlikely in that command: order, created = Order.objects.get_or_create(Customer=customer, complete=False).get() The following error occurs: FieldError at /cart/ Cannot resolve keyword 'Customer' into field. Choices are: complete, customUser, customUser_id, dateOrder, id, orderposition, shippingaddress, transactionID For that i created the class Customer in modely.py. enter image description here . I added "related_name = 'customer',related_query_name='customer'" but it did not fixed the issue. All the data is set in the database. From the Customer (i tried Customer as admin and without) to all products in my case cars are in the orderpositions of the order listed. Currently my def in views.py looks like this:enter image description here. When I try to open the cart this error appears: enter image description here. I can see that the Customer is listed as marked in img. Thx for your help! -
Exporting data of non-related with the model (Django Import-Export)
I'm using Django-import-export on django admin. I want to export the data that are not related. (Are related but it's weird..) Example: models.py class A(models.Model): name = models.CharField(default=False) size= models.CharField(default=True) class B(models.Model): relation = models.ForeignKey(A,on_delete=models.CASCADE) title = models.CharField(default=False) category = models.CharField(default=False) I want something like this: admin.py class export(resources.ModelResource): name = Field(column_name='something',attribute='name') category =Field(column_name='something_else',attribute='category') class Meta: model = A fields = ('name','category') class A_Admin(ExportActionMixin,admin.ModelAdmin): resource_class=export .... .... I need to get the data from model B that have a relation with A but A dont have relation with B... -
inspect.isfunction() in Python, is not working as intended
I was building a simple project in Django. Now inside an app, we have got the urls.py So out of curiosity, when I tried to find whether 'path' that I imported is a class or function, but everytime I got that its not a function. Everywhere (Stackoverflow post, or any other site) I am finding that the 'path' is a function. Can somebody explain this? Moreover, it is also printing 'False' for inspect.isclass(path) This is the content of 'urls.py' import inspect from django.urls import path print(inspect.isfunction(path)) It printed 'False', whereas it should have printed 'True', what happening actually? -
Django Raise Error When Slug Already Exist
I have a simple model like this: class MyModel(models.Model): title = models.CharField(max_length=255) slug = AutoSlugField(populate_from='title', unique=True, error_messages={'unique':"The slug of title has already been registered."}) I want to raise an error instead of creating a new slug whenever the slug already exist, but the error is not raised by the AutoSlugField I tried another way by override the save method of my model like this: def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Competition, self).save(*args, **kwargs) and validate it in my serializer like this: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' def validate_title(self, val): if MyModel.objects.filter(slug=slugify(val)).exists(): raise serializers.ValidationError('The slug of title has been registered.') return val This actually works fine while creating a new object but has a problem when updating the object, since if the slug remains the same it raises the error, but it should not because I am updating the same object. What is the most convenient way to do this? I really appreciate any help. Thank you... -
ConnectionRefusedError at /Contact-us/
When I tried to send an email in Django production, I got stuck with this error. ConnectionRefusedError at /Contact-us/ [Errno 111] Connection refused Request Method: POST Request URL: https://tigraygenocide.com/Contact-us/ Django Version: 5.0.1 Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connection refused Exception Location: /opt/alt/python311/lib64/python3.11/socket.py, line 836, in create_connection Raised during: App.views.Contact_us Python Executable: /home/ysu53cs929ka/virtualenv/public_html/tigray_genocide/3.11/bin/python3.11_bin Python Version: 3.11.5 Python Path: ['/home/ysu53cs929ka/public_html/tigray_genocide', '/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts', '/opt/alt/python311/lib64/python311.zip', '/opt/alt/python311/lib64/python3.11', '/opt/alt/python311/lib64/python3.11/lib-dynload', '/home/ysu53cs929ka/virtualenv/public_html/tigray_genocide/3.11/lib64/python3.11/site-packages', '/home/ysu53cs929ka/virtualenv/public_html/tigray_genocide/3.11/lib/python3.11/site-packages'] Server time: Sun, 21 Jan 2024 15:45:21 +0000 this is my django email configuration. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_PORT = 465 EMAIL_HOST_USER = 'tigraygenocide@tigraygenocide.com' EMAIL_HOST_PASSWORD = 'tigraygenocide2013' EMAIL_USE_SSL = True I tried to send email from the Django website using the Godaddy webmail configuration. -
Automatically change password in Django
I'm a Django developer and I want to change the password automatically by system. This is my python code data = form.cleaned_data passw = data["password"] print(datax) us = User.objects.get(email = datax) us.set_password(passw) us.save() when I run it, it doesn't save the password. what can I do? It doesn't save that new password. -
Migrations not reflecting after making Migrations in Django in Docker
I creating Django app and connect it with Docker along postgres db. While start with docker server is running fine but I did migrations by going into container of Django app but those migrations are not reflecting into DB(tables not created as per the model). # ======Docker compose.yml file=== version: '3' services: db: image: postgres environment: - POSTGRES_DB=eshop - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: admin_db volumes: - ./data/postgres:/var/lib/postgresql/data ports: - 54321:5432 web: build: . command: bash -c "python eshop/manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - "8000:8000" depends_on: - db enter image description here I want to know how to do migrations while django and postgres are runing using docker such that after migrations tables will be created in postgres -
Hosting Webapp for internal use within a small company
I'm developing a web app using Django and Vue.js intended for internal use within a small company (around 20 employees). I'm considering hosting it on a Platform-as-a-Service (PaaS) like Heroku or Netlify. My primary concern is ensuring that external users can't access the app and, ideally, can't log in even if they manage to access it. Currently, I'm relying on user authentication provided by Django. I'd like to know if Django's user authentication alone is sufficient for restricting access or if additional measures are commonly recommended for securing internal applications. Hosting it myself is less preferable due to the associated challenges, but I'm open to suggestions. What are the best practices in such scenarios? Thanks in advance for any guidance! For context: I'm still new at web app development. If anyone have some kind of cheatsheet for best practices in web development, i'd love to see it. Thx! -
Stripe payment not showing in Stripe dashboard after successful payment
I’m facing an issue with Stripe integration with my Django e-commerce website. Even though I followed the Stripe docs of accepting online payments, so when i open the checkout and complete the payment form, I get redirected to the success page. However, upon checking the Stripe dashboard for the payment, they are not showing. Also, I’m sending all the products at once and I’m loading the Stripe JS in my checkout. I'm not sure if I've set it up correctly. Is my integration complete? @login_required(login_url='core:login_register') def checkout(request): user_profile = request.user.userprofile cart = get_object_or_404(Cart, user=user_profile) total_price = cart.calculate_total_price() has_existing_billing_address = Address.objects.filter(user=user_profile).exists() form = CheckoutForm(request.POST or None) if request.method == 'POST' and form.is_valid(): order, _ = Checkout.objects.get_or_create(user=user_profile, cart=cart) default_billing_address = form.cleaned_data['use_default_billing_address'] if default_billing_address: billing_address = Address.objects.filter(user=user_profile, default=True).first() order.billing_address = billing_address else: new_billing_address = Address( user=user_profile, street_address=form.cleaned_data['street_address'], apartment_address=form.cleaned_data['apartment_address'], zip_code=form.cleaned_data['zip_code'], country=form.cleaned_data['country'], default=True ) new_billing_address.save() order.billing_address = new_billing_address order.save() payment_method = form.cleaned_data.get('payment_method') if payment_method: return redirect('core:payment', payment_method='card') context = { 'total_price': total_price, 'form': form, 'has_existing_billing_address': has_existing_billing_address, 'STRIPE_API_KEY': settings.STRIPE_SECRET_KEY, } return render(request, 'checkout.html', context) @login_required(login_url='core:login_register') def payment(request, payment_method): user_profile = request.user.userprofile cart = get_object_or_404(Cart, user=user_profile) billing_address_exists = Address.objects.filter(user=user_profile).exists() cart_items = cart.items.all() if not billing_address_exists: return redirect('core:checkout') line_items = [{ 'price_data': { 'currency': 'usd', 'product_data': { 'name': … -
Django LogoutView is not working. How to resolve this problem using classbased default function?
I want to use django buildin LogoutView library but it is not working. When i use this, it shows "This page isn’t working" The logout function should work and logout the user. Below is the urls.py code. from django.urls import path from .views import TaskList, TaskDetail, TaskCreate, TaskUpdate, DeleteView, CustomLoginView, RegisterPage, TaskReorder from django.contrib.auth.views import LogoutView urlpatterns = [ path('login/', CustomLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('register/', RegisterPage.as_view(), name='register'), path('', TaskList.as_view(), name='tasks'), path('task/<int:pk>/', TaskDetail.as_view(), name='task'), path('task-create/', TaskCreate.as_view(), name='task-create'), path('task-update/<int:pk>/', TaskUpdate.as_view(), name='task-update'), path('task-delete/<int:pk>/', DeleteView.as_view(), name='task-delete'), path('task-reorder/', TaskReorder.as_view(), name='task-reorder'), ] -
from . import views returning an attribute error
I created a python file in myapp and named it urls.py It looks like from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path("", views.home), path("predict/", views.predict), path("predict/result", views.result) Also I edited The project's urls.py as instructed an it now looks like from django import views from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path("", views.home), path("predict/", views.predict), path("predict/result", views.result) The views.py in myapp looks like def result(request): data = pd.read_csv(r"C:\Users\user\Desktop\MAX\diabetes.csv") X = data.drop("Outcome", axis=1) Y = data['Outcome'] X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) model = LogisticRegression(max_iter=1000) model.fit(X_train, Y_train) val1 = float(request.Get['n1']) val2 = float(request.Get['n2']) val3 = float(request.Get['n3']) val4 = float(request.Get['n4']) val5 = float(request.Get['n5']) val6 = float(request.Get['n6']) val7 = float(request.Get['n7']) val8 = float(request.Get['n8']) pared = model.predict([[val1, val2, val3, val4, val5, val6, val7, val8,]]) result1 = "" if pared == [1]: result1 = "positive" elif pared == [0]: result1 = 'negative' return render(request, "predict", {"result": result1}) I expected the server to run successfully -
'Account' object has no attribute 'user'
I was implementing django email verification.I'm facing an issue with 'Account' object has no attribute 'user'. 'token': default_token_generator.make_token(user), from django.shortcuts import render, redirect from .forms import RegistrationForm from .models import Account from django.contrib import messages, auth from django.contrib.auth.decorators import login_required #verification email from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes from django.contrib.auth.tokens import default_token_generator from django.core.mail import EmailMessage def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = email.split("@")[0] user = Account.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, password=password) user.phone_number = phone_number user.save() # USER ACTIVATION current_site = get_current_site(request) mail_subject = 'Please activate your account' verification_email_message = render_to_string('accounts/account_verification_email.html', { 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject, verification_email_message, to=[to_email]) send_email.send() messages.success(request, 'Registration Successful') return redirect('register') else: form = RegistrationForm() context = { 'form': form, } return render(request, 'accounts/register.html', context) def login(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) # messages.success(request,"You are now logged in.") return redirect('home') else: messages.error(request,'Invalid login credentials') return redirect('login') return render(request, 'accounts/login.html') @login_required(login_url … -
Js is loading but not running in django
I have been creating a website using django but when I try to access a js file in the static folder it doesn't work. However, in the python terminal I get the following message (meaning that the file is in fact loading but not running): [21/Jan/2024 10:07:14] "GET /static/CACHE/js/output.10e324644ab8.js HTTP/1.1" 304 0 Also, using the debug_toolbar library which I have added to my project I can see the file is loaded and I can open it. This is my html code: <html lang="en"> <head> {% load static %} {% load compress %} <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Centro Psi-Clinico Pisa</title> {% compress css %} <link rel="stylesheet" type="text/x-scss" href="{% static 'scss/base.scss' %}" /> {% endcompress %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="{% static 'js/main.js' %}"></script> </head> <body> <header>{% include 'navbar.html' %}</header> <main>{% block content %} {% endblock %}</main> </body> </html> -
Django IntegrityError - NOT NULL constraint failed: app_comments.author_id
I'm posting this after trying to find answers from other threads without luck. Seems like the form is missing some data, which I can't understand why. I'm using save(commit=False) also the author has null=True, blank=True Don't know what is app_comments.author_id my code: models.py class Comments(models.Model): content = models.TextField() name = models.CharField(max_length=200) email = models.EmailField(max_length=200) website = models.CharField(max_length=200) date = models.DateTimeField(auto_now=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) views.py def post_page(request, slug): post = Post.objects.get(slug=slug) form = CommentForm() if request.POST: comment_form = CommentForm(request.POST) if comment_form.is_valid: comment = comment_form.save(commit=False) post_id = request.POST.get('post_id') post = Post.objects.get(id=post_id) comment.post = post comment.save() if post.view_count is None: post.view_count = 1 else: post.view_count = post.view_count + 1 post.save() context = { 'post': post, 'form': form } return render(request, 'app/post.html', context) post.html <form method="POST"> {% csrf_token %} {{form.content}} <div class="grid-3"> <input type="hidden" name="post_id" value="{{post.id}}"> {{form.name}} {{form.email}} {{form.website}} </div> <button class="btn btn-primary rounded"> Post comment </button> </form> forms.py from django import forms from app.models import Comments class CommentForm(forms.ModelForm): class Meta: model = Comments fields = { 'content', 'email', 'name', 'website' } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['content'].widget.attrs['placeholder'] = 'Type your comment..' self.fields['email'].widget.attrs['placeholder'] = 'Email' self.fields['name'].widget.attrs['placeholder'] = 'Name' self.fields['website'].widget.attrs['placeholder'] = 'Website (optional)' The error: The above … -
HttpResponseRedirect is working but the distination template can't render out the html
I'm working on a twitter like website for practice purpose using django framework. in follow function, I use js to post a information back to my view to add a follow relation to my database. after that, it suppose to redirect back to original page. But it turns out the HttpResponseRedirect is working, but the destination template won't render the template out. I have to refresh the page manually. this is where HttpResponseRedirect happens here is the destination view this is the page of the follow function urls.py here we can see it actually redirect back to views.profile and print "hello" out, but it didn't render the template, I have to refreash it myself. Why? I tryed redirect to 'index' page, it still not working. maybe I can return render(request, 'network/profile')? but I will have to give it the whole dictionary again. -
Django Google Sign-in Issue: Cookies not saving when deploying backend
I am currently working on a Django project that involves Google sign-in functionality. The setup works perfectly when both the frontend and backend are running locally. However, when I deploy the backend and test the frontend locally, the tokens do not get saved in cookies. Here's a simplified overview of the relevant code: Certainly! Here's a template for your question on Stack Overflow: Title: Django Google Sign-in Issue: Cookies not saving when deploying backend Description: I am currently working on a Django project that involves Google sign-in functionality. The setup works perfectly when both the front end and back end are running locally. However, when I deploy the backend and test the front end locally, the tokens do not get saved in cookies. Here's a simplified overview of the relevant code: Backend (Django): class GoogleLoginApi(PublicApiMixin, ApiErrorsMixin, APIView): class InputSerializer(serializers.Serializer): code = serializers.CharField(required=False) error = serializers.CharField(required=False) def create_user_with_profile(self, user_email, user_info): try: user = User.objects.get(email=user_email) except User.DoesNotExist: user = User.objects.create_user( email=user_email, username=user_email.split("@")[0], first_name=user_info["given_name"], last_name=user_info["family_name"], password=User.objects.make_random_password(), ) user_profile = UserProfile.objects.create(user=user) save_image_from_url( user_profile, user_info["picture"], f"{user.username}.{user_profile.id}.jpg", ) return user def get(self, request, *args, **kwargs): input_serializer = self.InputSerializer(data=request.GET) input_serializer.is_valid(raise_exception=True) validated_data = input_serializer.validated_data code = validated_data.get("code") error = validated_data.get("error") login_url = f'{config("BASE_FRONTEND_URL")}/login' if error or not code: …