Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add urls from a Django app module into my main urls.py?
Hi So I'm learning a course but it's a bit date on Django 1 and I'm using Django 3. (I'm a newbie so didn't realize the difference) In one section, it says in my accounts app to make a new module for passwords. Then to create an init.py file and an urls.py. I've done this and I"ve created very standard Urls for password reset and change. And have also included the new templates in my project root directory templates folder under registration. This is my urls. py in my accounts/passwords folder from django.urls import path from django.contrib.auth import views as auth_views app_name='accounts.passwords' urlpatterns = [ path('password/change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password/change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password/reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password/reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password/reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password/reset/complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] In my main urls.py I've added path('accounts/', include("accounts.passwords.urls")), When I try it out it says there is no reverse match for the name, etc Password_reset_done. When I put the urls/paths directly into my main urls.py it works. So I wanted to check, how do I include the urls from a module in an app? I gave the app_name as "accounts.passwords" and also added that as an app in the settings on my main. Just thought I'd … -
Google Enterprise Recaptcha scored base metrics not recording the request
I followed the Frontend integration javascript example and it is clearly working. I was able to assess the token in my django backend which I received from grecaptcha.enterprise.execute with an action login. But when I look at the metrics of that site key the request or any analysis is not captured. -
Getting dynamic argument values in inherited class - django
am using paho mqtt written a class class initializer(): def __init__(self): self.client = mqtt.Client(mqtt_server+str(int(time.time()))) self.client.username_pw_set( username=mqtt_username, password=mqtt_password) self.client.on_connect = self.on_connect self.client.on_subscribe = self.on_subscribe self.client.connect(broker, mqtt_port) self.client.loop_start() def on_connect(self, client, userdata, flags, rc): if rc == 0: #app_logger.info("Device Connection Established") print("Device Connection Established") else: #app_logger.info("Bad Connection") print("Bad Connection") def on_message(self, client, userdata, message): # app_logger.info(message.topic) print("message.topic", message.payload) then i have inherited this class to another class. class PublishData(initializer): def __init__(self): super(PublishData, self).__init__() self.client.on_message = self.on_message def on_message(self, client, userdata, message): print("message.payloa", message.payload) def begin(self, topic, data): self.client.on_message = self.on_message self.client.subscribe( "topic") self.client.publish( topic, str(data)) publishData = PublishData() publishData.begin(topic, data) iam getting message in on_message function in initializer class. but not getting that message in inherited class.how to get the message.payload value in publishdata class -
How to transfer value between Django and MQTT
I have a django graph that will display some random value. I had subscribe to my mqtt topic and integrated into my django application. But the problem is how can I read the msg.payload in my views.py? I want my graph to show the value that published from MQTT. For your information, I create a py file to store my MQTT connection and loop it in my init.py. Views.py from django.shortcuts import render import random from paho.mqtt import client as mqtt_client def showdata(request): context = '''Here is where i need to put the (MQTT VALUE: msg.payload )''' return render(request, 'index.html', {'data': context}) MQTT.py import paho.mqtt.client as mqtt global test # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("Wind") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) test = msg.payload client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) Init .py from . import mqtt mqtt.client.loop_start() -
Communicating between two user's webpages
Let's say you have two users A and B logged into a website. I want user A to be able to trigger an action to automatically display certain web pages on user B's screen (either displaying new web content on the same page or re-directing the customer to a different page) - some sort of inter-website communication. I'm a novice developer so have absolutely no idea as to how to approach this. Would sincerely appreciate any possible solution (something that works with Python & Django or React & JS is preferable, if possible)!! Cheers! -
Is it possible to add dependent text and date field under a checkbox or a dropdown in django models
I want to know if I can directly make text and date fileds appear or connect when a dropdown (or a choice field) or a checkbox (boolean filed) is selected in django models. I know this can be done from the front end with javascript but i don't want to do it from the front end creating input fileds and use javascript to submit data. I have many fileds and if can do it directly from the django admin site then it reduces my burden. I am sharing only the part of the model that I want to act as mentioned above: models.py citation_type = ( ('SCC', 'SCC'), ('AIR', 'AIR'), ('AIOL', 'AIOL'), ('MLJ', 'MLJ'), ('Scale', 'Scale'), ('Supreme', 'Supreme'), ('A11CJ', 'A11CJ'), ('SCC(L&S)', 'SCC(L&S)'), ('FLR', 'FLR'), ('MhLJ', 'MhLJ') ) class Laws(models.Model): citations = models.Charfield(max_length = 255, choices= citation_type ,null=True) Now here I want that if someone for example chooses 'SCC' from the dropdown then one charfield and datefield related to SCC should appear that stores the data with to SCC. So when I dsiplay it in a html it should look like " citations: SCC (data in charfield)(data in data field) ". If it is not possilble with dropdowns even check boxes … -
Problem In Send Parameters of View to Lib
I have a problem for define def in Django. this is My View.py import logging from django.shortcuts import redirect from django.urls import reverse from django.views.generic import ListView from .models import Saham_Status, Saham_Pay from azbankgateways import bankfactories, models as bank_models, default_settings as settings from django.http import HttpResponse, Http404 from .forms import Saham_Pays from time import gmtime, strftime class SahamSta_ListView(ListView): template_name = 'forms/display_forms.html' context_object_name = 'saham_st' model = Saham_Status def get_queryset(self): return self.model.object.all().filter(user_name=self.request.user) def get_context_data(self, **kwargs): context = super(SahamSta_ListView, self).get_context_data(**kwargs) context['form'] = Saham_Pays return context class Sta_Pay_ListView(ListView): template_name = 'forms/statuse_pay.html' context_object_name = 'sta_pay' model = Saham_Pay def get_queryset(self): return self.model.objects.all().filter(user_name=self.request.user) def get_context_data(self, **kwargs): context = super(Sta_Pay_ListView, self).get_context_data(**kwargs) context['form'] = Saham_Pays return context #this part def get_payid(): pay_id = Saham_Status.object.all().filter(saham_pay_id=) return pay_id Now this is Lib in Django Lib for send parameters(p.py): def get_pay_data(self): data = { 'terminalId': int(self._terminal_code), 'userName': self._username, 'userPassword': self._password, 'orderId': int(self.get_tracking_code()), 'amount': int(self.get_gateway_amount()), 'localDate': self._get_current_date(), 'localTime': self._get_current_time(), 'additionalData': description, 'callBackUrl': self._get_gateway_callback_url(), 'payerId': get_payid() } return data and this models.py: class Saham_Status(models.Model): user_name = models.ForeignKey(User, on_delete=models.CASCADE) saham_pay_id = models.CharField(max_length=15, default=None) I want to send a parameter(saham_pay_id = field in db) of database that user login to p.py('payerId': get_payid()) and this function get_payid() defined in views.py. Help Me. -
Django forms.SelectMultiple ERROR: Select a valid choice. ['Internet bandwith'] is not one of the available choices
I am trying to implement my own form through a model that I have created, for some reason Django does not validate my form and it is related with forms.SelectMultiple (expense_category and expense_type) but none of the similar questions posted on SO could solve my problem. Basically I want a Select multiple (but allow only one selection). Code: forms.py: from django.forms import ModelForm from django import forms from expense.models import Expense class ExpenseForm(ModelForm): class Meta: model = Expense fields = ['project', 'contents', 'amount', 'currency', 'expense_date', 'store_company_client_name', 'expense_category', 'expense_type', 'note'] widgets = { 'project': forms.TextInput( attrs={ 'class': 'form-control' } ), 'contents': forms.TextInput( attrs={ 'class': 'form-control' } ), 'amount': forms.NumberInput( attrs={ 'class': 'form-control' } ), 'currency': forms.Select( attrs={ 'class': 'form-control', } ), 'expense_date': forms.TextInput( attrs={ 'class': 'form-control form-control-sm datetimepicker-input', 'style': 'font-size:14px;', 'name': 'month', 'placeholder': 'Select month', 'data-target': '#monthDatetimepicker' } ), 'store_company_client_name': forms.TextInput( attrs={ 'class': 'form-control' } ), 'expense_category': forms.SelectMultiple( attrs={ 'class': 'form-control' } ), 'expense_type': forms.SelectMultiple( attrs={ 'class': 'form-control' } ), 'note': forms.Textarea( attrs={ 'class': 'form-control', 'rows': '8' } ), } new_expense.html: <div class=" " style="font-size:14px;" > <div class="m-auto w-50"> <!-- modelform --> <div class="container"> <form method="POST"> {% csrf_token %} <!-- TIPS # --> <div class="d-flex flex-row "> <div class="d-flex w-25 p-1 … -
Arranging models fields according to our wish in django admin panel
Can I arrange this models according to my needs in Django admin panel dashboard. Now this is in alphabetical order , but I want to make my own arrangements. Can anybody help me how can I make that. Thank you. Please click this link below for the image. Django admin dashboard. -
my order items and order is being saved in the admin django , but is not been shown in the cart template, and quantity is not been updated to 3nos
Here, I am trying to add a product to the cart. But i am facing some issues. Firstly, the objects are not being rendered to the cart template which i want to add to cart, but in the admin django, the products can be seen there. However, the quantity of the product is not incrementing by itself. Two same products get added with nos 1, 2. however, when i try to add the same product thrice, then duplicacy happens of the 2nd added product .U can see the screenshot below : views.py: @login_required def add_to_cart(request, uid): item = AffProduct.objects.get(uid=uid) try: order_item = OrderItem.objects.create( item=item, user=request.user, ordered=False ) except: order_item = None order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__uid=item.uid).exists(): order_item.quantity = order_item.quantity + 1 order_item.save() print(order_item) messages.info(request, "This item quantity was updated.") return redirect("cart") else: order.items.add(order_item) print(order_item) messages.info(request, "This item was added to your cart.") return redirect("cart") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.create(order_item) print(order_item) messages.info(request, "This item was added to your cart.") return redirect("cart") models.py class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(AffProduct, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): … -
Django admin template bug
Today I installed django==3.2.6 LTS for a new project, but I faced this template of admin. Is is correct or it's a bug? -
Make foreign key editable in your formset
I'm really struggling with django-forms. In particular, I'd like to have a formset of my OrderMedia model, where the foreignkey to contactMethod is also editable (a form). Models.py: class OrderMedia(models.Model): CHOICES = ( ('IDB', _('IDB')), ('E', _('E')), ) contactMethod = models.ForeignKey('BusinessContactMethod', on_delete=models.CASCADE) publication = models.BooleanField(default=True) management = MultiSelectField(choices=CHOICES, blank=True) to_create = models.BooleanField(default=False) from_order = models.ForeignKey('Order', on_delete=models.CASCADE) class BusinessContactMethod(models.Model): medium = models.ForeignKey(ContactMedium, on_delete=models.CASCADE) value = models.CharField(max_length=100, blank=True, null=True) active = models.BooleanField(default=True) Views.py: class NewOrderPart2(View): form_class = OrderForm template_name = 'orders/new_order_part2.html' def get(self, request, *args, **kwargs): est_number = self.kwargs['est_number'] order = Order.objects.get(est_number=est_number) MediumFormset = inlineformset_factory(Order, OrderMedia, exclude=[''], extra=1, can_delete=True) mediums = MediumFormset(instance=order) form = self.form_class(instance=order) return render(request, self.template_name,{ 'form': form, 'mediums': mediums, }) def post(self, request, *args, **kwargs): est_number = self.kwargs['est_number'] order = Order.objects.get(est_number=est_number) MediumFormset = inlineformset_factory(Order, OrderMedia, exclude=[''], extra=1, can_delete=True) mediums = MediumFormset(request.POST, instance=order) form = self.form_class(request.POST, instance=order) if mediums.is_valid(): mediums.save() print(mediums) if form.is_valid(): form.save() return HttpResponseRedirect(f'/order/{est_number}') return render(request, self.template_name, { 'form': form, 'mediums': mediums, }) Forms.py: class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' widgets = { 'order_start': DateInput, 'order_end': DateInput, 'order_publication': DateInput, 'contact_signed_date': DateInput, } Template: <form method="POST"> <div id="form_set"> {% for form in mediums.forms %} <div class='custom-select'> {{form }} <div> {% endfor %} </div> </form> I've … -
AWS EC2 instance Django project
my website is not connecting to was ec2 instance 2:nginx also not giving any error 3: gunicorn giving no error security group, port allowed HTTP and https -
AttributeError at /blog/create/blog-post
I am learning django but this error has made me sick. I wanted to create a form to register a new blog post. But I get this weird error nobody seems to have got. I'm really a begginer in django. Here's the trace: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/blog/create/blog-post Django Version: 3.2.6 Python Version: 3.9.6 Installed Applications: ['blog', 'django_summernote', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "C:\My_Stuff\Blogistan\env\lib\site- packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\My_Stuff\Blogistan\blog\views.py", line 19, in BlogPostForm form = BlogPostForm(request.POST or None) File "C:\My_Stuff\Blogistan\blog\views.py", line 19, in BlogPostForm form = BlogPostForm(request.POST or None) Exception Type: AttributeError at /blog/create/blog-post Exception Value: 'NoneType' object has no attribute 'POST' Here's my console: Internal Server Error: /blog/create/blog-post Traceback (most recent call last): File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\My_Stuff\Blogistan\blog\views.py", line 19, in BlogPostForm form = BlogPostForm(request.POST) File "C:\My_Stuff\Blogistan\blog\views.py", line 19, in BlogPostForm form = BlogPostForm(request.POST) AttributeError: 'QueryDict' object has no attribute 'POST' My views.py: def BlogPostForm(request): form = BlogPostForm(request.POST) … -
HINT: Add or change a related_name argument to the definition for 'student_management_app.CustomUser.user_permissions' or 'auth.User.user_permissions'
I have added AbstractUser and imported according in Django models.py to but getting the error? help appricated. models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class CustomUser(AbstractUser): user_type_data=((1, "HOD"), (2, "Staff"), (3, "Student")) user_type=models.CharField(default=1,choices=user_type_data, max_length=10) class AdminHOD(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) name=models.CharField(max_length=255) email=models.CharField(max_length=255) password=models.CharField(max_length=255) created_at=models.DateField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class Staffs(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) name=models.CharField(max_length=255) email=models.CharField(max_length=255) password=models.CharField(max_length=255) address=models.TextField() created_at=models.DateField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class Courses(models.Model): id=models.AutoField(primary_key=True) course_name=models.CharField(max_length=255) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class Subjects(models.Model): id=models.AutoField(primary_key=True) subject_name=models.CharField(max_length=255) course_id=models.ForeignKey(Courses, on_delete=models.CASCADE) staff_id=models.ForeignKey(Staffs, on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class Students(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) name=models.CharField(max_length=255) email=models.CharField(max_length=255) password=models.CharField(max_length=255) gender=models.CharField(max_length=255) profile_pic=models.FileField() address=models.TextField() course_id=models.ForeignKey(Courses, on_delete=models.DO_NOTHING) session_start_year=models.DateField() session_end_year=models.DateField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class Attendance(models.Model): id=models.AutoField(primary_key=True) subject_id=models.ForeignKey(Subjects, on_delete=models.DO_NOTHING) attendance_date=models.DateTimeField(auto_now_add=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class AttendanceReport(models.Model): id=models.AutoField(primary_key=True) student_id=models.ForeignKey(Students, on_delete=models.DO_NOTHING) attendance_id=models.ForeignKey(Attendance, on_delete=models.CASCADE) status=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class LeaveReportStudent(models.Model): id=models.AutoField(primary_key=True) student_id=models.ForeignKey(Students, on_delete=models.CASCADE) leave_date=models.CharField(max_length=255) leave_message=models.TextField() leave_status=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class LeaveReportStaff(models.Model): id=models.AutoField(primary_key=True) staff_id=models.ForeignKey(Staffs, on_delete=models.CASCADE) leave_date=models.CharField(max_length=255) leave_message=models.TextField() leave_status=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class FeedBackStudent(models.Model): id=models.AutoField(primary_key=True) student_id=models.ForeignKey(Students, on_delete=models.CASCADE) feedback=models.TextField() feedback_reply=models.TextField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class FeedBackStaff(models.Model): id=models.AutoField(primary_key=True) staff_id=models.ForeignKey(Staffs, on_delete=models.CASCADE) feedback=models.TextField() feedback_reply=models.TextField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class NotificationStudent(models.Model): id=models.AutoField(primary_key=True) student_id=models.ForeignKey(Students, on_delete=models.CASCADE) message=models.TextField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() class NotificationStaffs(models.Model): id=models.AutoField(primary_key=True) staff_id=models.ForeignKey(Staffs, on_delete=models.CASCADE) message=models.TextField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() Note: Error when I migrate the data using python3 manage.py makemigrations then … -
Django sending a None query to SQL
I have a Django (v2.2.23) application connected to a MySQL (v5.7) database. Every now and then, for a few minutes at a time, all my DB queries start to fail with one of the following errors: "Unknown MySQL Error" (error code 2000), "InterfaceError", or "Malformed Packet" (error code 2027). The errors resolve themselves on their own after a few minutes, but then they pop up again a some time later (on average, every few hours). These errors happen seemingly at random and I haven't found any reliable way to reproduce them till now. There is nothing wrong with the code as far as I can see because when the queries do execute, they work as expected and give the correct results. I have already made several attempts to fix the issue to no avail, including :- Following all the steps given in this article Increasing the value of connect_timeout and wait_timeout Changing the charset used in the table in my DB (tried latin1 and utf8) Upgrading the Python mysqlclient package to the latest version (2.0.3) This error is occuring both on local and staging environments. In order to debug this further, I create a custom exception handler and logged the … -
django tables2 is there a way to use text box to edit searched result?
I have been searching for grid data tool that can display, sort and edit datas on each cells(multiple rows at same time as well). Apparently, I can just use good old html table to display and add field for edit and delete button to modify or delete data 1 row at a time but modifying data requires to make new edit page and not being able to edit multiple row at same time is very annoying. I try to make django tables2 but while this is good table to display and sort datas or use with filters but it seems it does not allow me to edit cells and update multiple rows at same time. Is there way to achieve this on django tables2 or is there another apps or module that can do this? I even searched for paid one but they work with react or angular not with django. If there is way to make it work with django tables2, that would be great but if not, I am willing to use anything I can find. I suspect grid data tool has to be javascript based to achieve what I want.. I need something similar to AG Grid … -
Django Server Run Permanent
I have an Django-React Project. I use React project build file in my Django project to run project together. When ı use; python manage.py runserver 0.0.0.0:8000 command in my linux server there is no any problem. My projects works well. I want to run my project permanent. I use; screen -d -m python manage.py runserver 0.0.0.0:8000 command. It works without any problem but after a certain time the project stops working. Is there any opinion to run my project permanetly without any problem like run server command. -
Django doesn't validate my form with a valid request.POST
I am trying to implement my own form through a model that I have created, for some reason Django does not validate my form. I have been debugging and I don't see anything weird in the request.POST. Could someone tell me what am I doing wrong? views.py: @login_required def new_expense(request): data = { 'title': "New Expense", } data['projects'] = Project.objects.filter(is_visible=True).values('id') form = ExpenseForm() if request.method == "POST": print(request.POST) form = ExpenseForm(request.POST) if form.is_valid(): form.save() data['form'] = form return render(request, "expense/new_expense.html", data) This is what I am getting when I print(request.POST): <QueryDict: {'csrfmiddlewaretoken': ['oym6pyM3CAsIBovdWioItcJIvrsl8kf8fLkbyuVtZmhSr9SOW5o8RN9rpZE0SmTY'], 'project': ['100001'], 'contents': ['Testing'], 'amount': ['666'], 'currency': ['JPY'], 'expense_date': ['09/23/2021'], 'store_company_client_name': ['Some test'], 'expense_category': ['Leases'], 'expense_type': ['Phone lease'], 'note': ['dummy note']}> [20/Aug/2021 15:00:56] "POST /new_expense/ HTTP/1.1" 200 18384 models.py: from django.db import models from django.contrib.auth.models import User from project.models import Project from expense.constants import * class Expense(models.Model): user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL, ) project = models.TextField( blank=True, null=True, default=None ) contents = models.TextField( null=True, default=None ) amount = models.IntegerField() currency = models.CharField( choices=CURRENCIES, default=CURRENCY_JPY, max_length=20, null=True, ) expense_date = models.DateTimeField() store_company_client_name = models.TextField( blank=True, null=True, default=None ) expense_category = models.CharField( choices=EXPENSE_CATEGORY, default=EXPENSE_STAFFING_PAYMENTS, max_length=200, null=True, ) expense_type = models.CharField( choices=EXPENSE_TYPE, default=EXPENSE_PRINTER_LEASE, max_length=200, null=True, ) note = … -
Sending web content from one page instance to another page instance (inter-website communication)
I have a project idea but got no clue how I should go about building it. Let's say you have businesses and customers logged into my website, each with their respective webpage view. A business can scan a customer's paper coupon barcode, which will then trigger an action to automatically display certain interactable webpages on the customer's screen (either displaying new web content on the same page or re-directing the customer to a different page). Each business will want to display different content on the customer's screen. It's safe to assume that both the business and the user will be logged in when this "trigger" occurs. Essentially, I want to have some sort of inter-website communication. I'm a novice developer so have absolutely no idea as to how to approach this. Would sincerely appreciate any possible solution (something that works with Python & Django or React & JS is preferable, if possible)!! Cheers! -
exporting html template to excel in django
I am trying to make a button that exports html table data to excel. I want to get the data from what is shown in the template but I got all the data from my database here is my views.py def export_excel(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=rate_analysis.xls' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('rate_analysis') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['columns ...'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = CompanyRate.objects.values_list('date', 'notice_name', 'event', 'basic_amount', 'num_of_company', 'avg_of_1365', 'hd_rate', 'hd_num', 'hj_rate', 'hj_num', 'hm_rate', 'hm_num') for row in rows: row_num+=1 for col_num in range(len(row)): ws.write(row_num, col_num, str(row[col_num]), font_style) wb.save(response) return response and this is my table data {% for companyrate in company_list %} <tr style="text-align: left"> <td>{{ companyrate.date }}</td> <td>{{ companyrate.notice_name }}</td> <td>{{ companyrate.event }}</td> <td>{{ companyrate.basic_amount }}</td> <td>{{ companyrate.num_of_company }}</td> <td>{{ companyrate.avg_of_1365 }}</td> <td>{{ companyrate.hd_rate }}</td> <td>{{ companyrate.hd_num }}</td> <td>{{ companyrate.hj_rate }}</td> <td>{{ companyrate.hj_num }}</td> <td>{{ companyrate.hm_rate }}</td> <td>{{ companyrate.hm_num }}</td> </td> </tr> I have no idea to get the data from html template please help thank u and im sorry that im not good at english -
how to check wether a user login for firsr time or not in django so i can rediect him to another page then usual
i want user to redirect to a from page where he has to submit detail if he is logged in site for first time or if a already a user for sometime and logged in before he will redirect to normal home page so any idea how can i achieve that in django here is my login views def my_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] remember_me = form.cleaned_data['remember_me'] user = authenticate(username=username, password=password) if user: login(request, user) if not remember_me: request.session.set_expiry(0) return redirect('accounts:home') else: request.session.set_expiry(1209600) return redirect('accounts:home') else: return redirect('accounts:login') else: return redirect('accounts:register') else: form = LoginForm() return render(request, "login.html", {'form': form}) i want user to redirect to this form if he is logging in site for first time @login_required def add_address(request, username): if request.method == 'POST': form = Addressform(request.POST) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('accounts:home') else: form = Addressform() return render(request, 'add_address.html', {'form': form}) other wise then to normal home page i have also seen a same stackoverflow question where the are using signals but i dont really get how to implement in my code where session expiry is decided by user -
Djano: DATABASES IMPROPERLY CONFIGURED, Please supply engine value. (Multiple databases)
Hey guys I am trying to have 2 postgres databases in my django project, one to hold user data and the other to hold other contents, but I am getting this error when I try to run createsuperuser. raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. This is settings.py DATABASES = { 'default': {}, 'users_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'users_db', 'USER': 'postgres', 'PASSWORD': 'Trial_user123', 'HOST':'127.0.0.1', 'PORT':'5432', }, 'content_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'content_II', 'USER': 'postgres', 'PASSWORD': 'Trial_user123', 'HOST':'127.0.0.1', 'PORT':'5432', }, } DATABASE_ROUTERS = ['personal.routers.db_routers.AuthRouter', 'personal.routers.db_routers.PersonalDBRouter', ] This is the router class AuthRouter: route_app_labels = {'sessions', 'auth', 'contenttypes', 'admin', 'accounts'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'users_db' return None def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'users_db' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return 'users_db' return None class PersonalDBRouter: route_app_labels = {'actions', 'blog', 'token_blacklist', 'taggit', 'django_celery_beat', 'django_celery_results',} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'content_db' return None def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: … -
Django REST - Ex1 - Serialization
We had given task for Django REST - Ex1 - Serialization, task is attach in below screen shot - Task Detail For the same task we had written code as - from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse from rest_framework.parsers import JSONParser from wishes.models import Wish from wishes.serializers import WishSerializer @csrf_exempt def wish_list(request): pass """ List all wishes or create a new wish """ if request.method == 'GET': serializer = WishSerializer(Wish) serializer.data return JsonResponse(serializer.data) #Write method Implementation here if request.method == 'POST': pass #Write method Implementation here @csrf_exempt def wish_detail(request,pk): pass """ Retrieve, update or delete a birthday wish. """ try: wish = Wish.objects.get(pk=pk) except Wish.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': pass #Write method Implementation here elif request.method == 'PUT': pass #Write method Implementation here elif request.method == 'DELETE': pass #Write method Implementation here Our concerns related to code part is serializer = WishSerializer(Wish) serializer.data return JsonResponse(serializer.data) in this serializer = WishSerializer(Wish) having error as - Too many positional arguments for function callpylint(too-many-function-args) when we execute required code then we getting error as below. Hence we need expertise advice what went wrong in our code- self.assertEqual(res.status_code, row['response']['status_code']) AssertionError: 500 != 200 Stdout: {'response': {'body': [], 'headers': {'Content-Type': 'application/json'}, … -
Ecommerce Application Cart Getting Empty after Logout
Hi i am new to react please help me guys .. i am getting my cart empty after signout and i dont want it to happen i mean i dont want to make my cart empty automatically after signout i want all my items/products be there right there in my cart even if i logout..!! do i need to handle it from nackend or else i can do it from frontend i am confused i am using react for the very first time so i am getting confused ** ** Index.js export const signout = (next) => { const userId = isAuthenticated() && isAuthenticated().user.id; console.log("USERID: ", userId); if (typeof window !== undefined) { localStorage.removeItem("jwt"); cartEmpty(() => {}); //next(); return fetch(`${API}user/logout/${userId}`, { method: "GET", }) .then((response) => { console.log("Signout success"); next(); }) .catch((err) => console.log(err)); } }; Cart.js export const addItemToCart = (item,next) => { let cart = []; if (typeof window !== undefined){ if(localStorage.getItem("cart")){ cart = JSON.parse(localStorage.getItem("cart")) } cart.push({ ...item, }); localStorage.setItem("cart", JSON.stringify(cart)); next(); } } export const loadCart =() => { if(typeof window !== undefined){ if(localStorage.getItem("cart")) { return JSON.parse(localStorage.getItem("cart")) } } }; export const removeItemFromCart = (productId) => { let cart = []; if (typeof window !== undefined){ if(localStorage.getItem("cart")) …