Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change user based on their personal value using python
I have a table in my models named as Referralcode ReferralActiveUser class ReferralActiveUser(models.Model): user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) user_active = models.BooleanField(default=False) referral = models.ForeignKey( User, related_name='comp_active_user', on_delete=models.SET_NULL, null=True, blank=True) I want to loop over this table and change the status of user based on their pv(personal value) but I'am confused or I don't know how to do this. What I want is assume this is a users in my table [ { "id": 1, "user": 2, "user_active": "0", "referral_by": 1 }, { "id": 2, "user": 3, "user_active": "0", "referral_by": 2 }, { "id": 3, "user": 4, "user_active": "0", "referral_by": 2 }, { "id": 4, "user": 5, "user_active": "0", "referral_by": 2 } ] here "user":1 is first user who started this program and all other users are child of "user":1 it's like tree structure and I want to loop over user and check each user pv and change it's status like this referral_users = ReferralActiveUser.objects.all() min_value=20 for user in referral_users: if user.pv >= min_value: user.status = True user.save() else: # Find users referred by this user inactive_users = referral_users.filter(referral_by=user.user) for j in inactive_users: j.referral_by = # want to add parent of this user j.save() user.status = False user.save() INFO … -
Change chunk_vendors/app js file import urls in public index.html in a Django/Vue application
I want to serve my chunk vendors or app js files under static/js/chunk_vendors.js rather than /js/chunk_vendors.js because I want to point to the dist directory generated for production build by npm run build and my static url in Django is /static so every static file should be access via a url starting with /static. But npm run build generates an html file with chunk_vendors.js url /js/chunk_vendors.js. How can I tell Vue Cli to generate html files with /static prefix? -
m2m_change signal not work form admin site but work from shell
I have a model class Category(models.Model): name = models.CharField(unique=True, max_length=45, blank=False, null=False) perants= models.ManyToManyField('self',through="CategoryParent",symmetrical=False,blank=True) and the CatigoryPerants is : class CategoryParent(models.Model): chiled_filed=models.ForeignKey("Catigory", on_delete=models.CASCADE,related_name="parent_of_category",blank=False) parent_filed=models.ForeignKey("Catigory", on_delete=models.CASCADE,blank=False) and I try to run a signal in signal.py: @receiver(m2m_changed, sender=Catigory.perants.through ) def CatigoryParentSignals(sender, instance, action, pk_set, **kwargs): print("Some text or throw Validation Expiation or doin any thing") The problem is when I add new parent to the Category from Shell with .parents.set([parents]) or.parants.add(parent) its work but when add any parent from admin site this signal isn't work -
Django REST Frameworking: modify PrimaryKeyRelatedField queryset for GET requests
Is it possible to give PrimaryKeyRelatedField a get_queryset function that is called when doing a GET request? Currently it's only getting called when I'm doing a POST or PUT request, but I want to be able to limit which relations get shown in a GET request, or as the result of a PUT or POST request. The use case is that I have a model with a many to many relationship, some of which the user has access to, and some not. So I want to only include the ones the user has access to in the result. Specifically, take this example: class Quest(models.Model): name = models.CharField(max_length=255) is_completed = models.BooleanField(default=False) characters = models.ManyToManyField(Character, blank=True) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) class Character(models.Model): name = models.CharField(max_length=255) is_hidden = models.BooleanField(default=False) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) So a quest has an array of characters, some of which can be marked as hidden. My serializer looks like this: class QuestSerializer(DmNotesModelSerializer): characters = CharacterPrimaryKeyRelatedField(many=True) class Meta: model = Quest fields = "__all__" class CharacterPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Character.objects.filter(campaign_id=self.context.get("view").kwargs.get("campaign_id")) This makes the characters array writable, AND I am limiting the characters you can add to ones that belong to the same campaign as the quest itself. This … -
Using the Django Admin Template
I'm trying to use the Django admin templates to login in some users in my website. The point is: I wouldn't like to create my own templates (.html) so I'm trying to find out a way to make it simple! Here is my admin.py inside auditoria.app from auditoria_app.urls import app_name class AuditoriaAdminArea(admin.AdminSite): site_header = 'Área Restrita' site_url = app_name auditoria_site = AuditoriaAdminArea(name='AuditoriaAdmin') My urls.py inside auditoria_app from . import views app_name = 'auditoria_app' urlpatterns = [ # Home Page path('', views.index, name='index'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My urls.py from auditoria_app.admin import auditoria_site urlpatterns = [ path('admin/', admin.site.urls), ##path('', include('auditoria_app.urls')), ## this is the correct urls after logged in path('', auditoria_site.urls), ] After the login is completed, Django is redirecting the user to the Admin Panel. How can I redirect them to my home page instead? Cheers! -
accessing self.request.user.profile in django generic views
I'm working on an API in Django rest framework and I am using generics.RetrieveUpdateAPIView here is my class: class updateProfile(generics.RetrieveUpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer and here is my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) short_intro = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField( null=True, blank=True, upload_to="profiles/", default="profiles/user-default.png", ) social_github = models.URLField( max_length=200, blank=True, null=True, validators=[validate_url_github] ) social_twitter = models.URLField( max_length=200, blank=True, null=True, validators=[validate_url_twitter] ) social_linkedin = models.URLField( max_length=200, blank=True, null=True, validators=[validate_url_linkedin] ) social_youtube = models.URLField( max_length=200, blank=True, null=True, validators=[validate_url_yt] ) social_website = models.URLField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False ) I want to access the request.user.profile I have tried the view as : class updateProfile(generics.RetrieveUpdateAPIView): queryset = request.user.proifle //and also self.request.user.proile serializer_class = ProfileSerializer how can I access the profile of the user in this class-based view -
Not getting all field in Django form to enter the details
I wanted to use my both models farmer(Foreign key for tractor) and tractor in a single form but i am not getting the fields of tractor in web page to enter its value i am only getting fields of farmer. my models.py class Farmer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone =models.CharField(max_length=10) address = models.TextField(max_length=200) email_address = models.EmailField() def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name() class Post(models.Model): tractor_price = models.IntegerField(max_length=150) implimentaion = models.CharField(max_length=50) purchase_date = models.DateField(auto_now=False) slug = models.SlugField(unique=True, db_index=True, null=True,blank=True) tractor_company = models.CharField(max_length=50) tractor_model = models.CharField(max_length=50) description = models.TextField(validators=[MinLengthValidator(10)]) date = models.DateField(auto_now_add =True) farmer = models.ForeignKey( Farmer, on_delete=models.SET_NULL, null=True, related_name="posts") my view.py Only add_post function def add_post(request): if(request.method == "POST"): farmer_form = FarmerForm(request.POST) post_form = Post(request.POST) if(farmer_form.is_valid() and post_form.is_valid()): farmer = farmer_form.save() post = post_form.save(False) post.farmer = farmer post.save() return redirect(reverse("tractor.views.posts")) else: farmer_form = FarmerForm(request.POST) post_form = Post(request.POST) args = {} args.update(csrf(request)) args["farmer_form"] = farmer_form args["tractor_form"] =post_form return render(request,"tractor/form.html",args) forms.html <div class="form-group"> <form method="POST" style="margin-left: 40px; margin-right: 100px" enctype="multipart/form-data" action="{% url 'tractor:add_post' %}" > {% csrf_token %} {{post_form}} {{farmer_form}} <input type="submit" class="btn btn-dark" value="Submit" /> </form> </div> forms.py class PostForm(ModelForm): class Meta: model = Post fields = ("tractor_price","implimentaion","purchase_date","tractor_company","tractor_model","description") class FarmerForm(ModelForm): class Meta: model = Farmer fields = … -
is the any other way to upload image from frontend using upload section ? getting not displayed and upload from index.html page
I have tried to upload the image from the index.html page and also created; modles.py, views.py, urls.py and soon but I have upload and it is successfully uploaded in the mentioned directory in models.py but failed to view that image in front showing cut pic image views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Upload # Create your views here. # Imaginary function to handle an uploaded file def Home(request): if request.method == 'POST': photo = request.POST['doc'] Upload.objects.create(document = photo) context ={ } if request.method == "GET": photo = Upload.objects.all() context = { 'phone': photo } return render(request, 'Home.drive.html', context) models.py from django.db import models # Create your models here. class Upload(models.Model): document = models.ImageField(upload_to='documents') index.html {% load static %} <!DOCTYPE html> {% block content %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>PB-2021</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/index.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-5.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/> </head> <body> <nav style="font-size: 1em; list-style-type: none; display: block; margin: 0; padding: 0; overflow: hidden; position: sticky; top: 0; z-index: 1;"> <input type="checkbox" id="check"> <label for="check" class="checkbtn"> <i class="fas fa-bars"></i> </label> <label class="logo">AMRIT SHAHI</label> <ul> <li><a class="active" href="{% url 'PBAPP:home' %}">Home</a></li> <li><a href="#">About</a></li> <li><a … -
Django logout is not logging out user
I have done a lot of searching and all I can really find are variants of the following: from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page. Here is the code from my view: from django.contrib.auth import logout def leave(request): logout(request) return redirect("index") However, it neither logs the user out nor goes to the index page. I also have: path('accounts/', include('django.contrib.auth.urls')), in my urls page. I tried prefixing my urls with "accounts/" but that just resulted in errors. -
I'm using python apscheduler in django to remind users of created notices. I'm stuck at trying to make the date that they want to be reminded dynamic
My task is to create reminders for notices. If I hardcode, I get the reminder on the cli from the API but I want to make it dynamic so users can pick the date or time they want to be reminded of their notice. Please help! This is the updater.py file from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler from .jobs import notice_reminder def notice_me(): notice_remind = notice_reminder.newly_created_notice_reminder if notice_remind: print(notice_remind) else: print("No recent notice reminders!") """ The dummy data """ dynamic_data = [ { "title": "Notice Reminder", "schedule_time": "00:50:00", "schedule_date": "10-2-2021" } ] print(dynamic_data[0].get("schedule_date")) # Get Date and Time Dynamically dynamic_data = notice_reminder.newly_created_notice_reminder if any(notice_reminder.newly_created_notice_reminder) else "dynamic_data" dynamic_date_time = f"{dynamic_data[0].get('schedule_date')} {dynamic_data[0].get('schedule_time')}" print(f"Date Time: {dynamic_date_time}") dynamic_date = datetime.strptime(dynamic_date_time, '%m-%d-%Y %H:%M:%S') print(f"Dynamic Date Time: {dynamic_date}") def start(): scheduler = BackgroundScheduler() scheduler.add_job( notice_me, "date", run_date = f"{dynamic_date}" ) scheduler.start() This is my serializer file for the view notices option from rest_framework import serializers from django.utils import timezone from datetime import date # Time Zone time = timezone.now() # Get Current Time current_time = f"{time.hour + 1}:{time.minute}:{time.second}" # Get Current Date current_date = f"{time.month}-{time.day}-{time.year}" class NoticeReminderSerializer(serializers.Serializer): title = serializers.CharField(max_length=255) time_created = serializers.TimeField(default=current_date) date_created = serializers.DateField(default=current_time) schedule_time = serializers.TimeField() schedule_date = serializers.DateField() This is … -
Django with Javascript es6 resource not working
enter image description here Hi,I recently developed a 3D model project based on THREEJS,using es6 gramar. It's works fine with tomcat,and nodejs http-server but it can't work on python backend ,Django Framework. Give me this error above. There's no CORS problem since the static resource runs on server -
Decision in Back-end [closed]
I have an important question. How can I understand when using Go, Django, PHP, Java, or another language for Back-end. I am really confused. Please explain to me the parameters which are important for the decision. -
Django aggregate sum throwing `int() argument must be a string, a bytes-like object or a number, not 'dict'`
I am trying to create a serializer to aggregate some data regarding a users inventory, however it is throwing the following error: Exception Value: int() argument must be a string, a bytes-like object or a number, not 'dict' I am not sure what time missing here. I am trying to sum the fields of standard and foil for a given user. Model.py class inventory_tokens(models.Model): ... standard = models.IntegerField(default=0) foil = models.IntegerField(default=0) serializers.py class InventorySerializers(serializers.Serializer): total_Cards_Unique = serializers.IntegerField() total_Cards = serializers.IntegerField() total_Standard = serializers.IntegerField() total_Foil = serializers.IntegerField() views.py # Inventory Data class InventoryData(views.APIView): def get(self, request): user_id = self.request.user data = [{ "total_Cards_Unique": inventory_cards.objects.filter(user_id=user_id).count(), "total_Cards": 0, "total_Standard": inventory_cards.objects.filter(user_id=user_id).aggregate(Sum('standard')), 'total_Foil': inventory_cards.objects.filter(user_id=user_id).aggregate(Sum('foil')), }] results = InventorySerializers(data, many=True).data return Response(results) full traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/account/inventory/inventory-data/ Django Version: 3.2.7 Python Version: 3.7.9 Installed Applications: ['base.apps.BaseConfig', 'account.apps.AccountConfig', 'administration.apps.AdministrationConfig', 'magic.apps.MagicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'psycopg2', 'background_task', 'rest_framework'] 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 "W:\My Drive\Projects\Card Companion\card_companion\card_companion_venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "W:\My Drive\Projects\Card Companion\card_companion\card_companion_venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "W:\My Drive\Projects\Card Companion\card_companion\card_companion_venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "W:\My Drive\Projects\Card Companion\card_companion\card_companion_venv\lib\site-packages\django\views\generic\base.py", line … -
Django axes limit a custom model
I use SMS verification service in my project and I would like to prevent any abuse to this. I already implemented Axes to track and limit login attempts. How if I want to track/limit attempts to this service as well? Thanks! -
How to make pagination when send POST Form to Django View
I'd like to use paginations in django when send post method to my view: It returns the values properly when click in submit, but when I click in "next page" it returns empty table. html: <form action="{% url 'maintenance_issue_search' %}" method="POST" enctype="multipart/form-data" id="form" name="form"> {% csrf_token %} <div style="text-align:left;" class="form-row"> <div class="form-group mr-2"> <label for="date">Date Start</label> <input class="form-control" id="date" name="date" placeholder="YYYY-MM-DD" value="{{ start_date }}" type="date" required> </div> <div class="form-group mr-2"> <label for="date1">Date End</label> <input class="form-control" id="date1" name="date1" placeholder="YYYY-MM-DD" value="{{ end_date }}" type="date" required> </div> <div style="text-align:left;" class="form-group"> <label for="select_status">Status</label> <select name="select_status" id="select_status" style="float:left;" class="form-control" multiple> <option value="Pending" selected>Pending</option> <option value="On Going">On Going</option> <option value="Consent OK">Consent Ok</option> <option value="Approve OK">Approve Ok</option> <option value="Completed">Completed</option> <option value="Not Approved">Not Approved</option> </select> </div> <section class="buttons"> <div style="text-align:center;float:left" class="form-group"> <div class="form-group col-md-6"> <button type="submit" class="btn btn-info">Search </button> </div> </div> </section> </div> </form> <!--Pagination--> {% if issue_list.has_other_pages %} <ul class="table-pagination"> {% if issue_list.has_previous %} <li><a href="?page=1">First</a></li> <li><a href="?page={{ issue_list.previous_page_number }}">Previous</a></li> {% endif %} <span class="current"> Page {{ issue_list.number }} of {{ issue_list.paginator.num_pages }} </span> {% if issue_list.has_next %} <li><a href="?page={{ issue_list.next_page_number }}">Next></a></li> <li><a href="?page={{ issue_list.paginator.num_pages }}">Last></a></li> {% endif %} </ul> {% endif %} Views: def maintenance_issue_search(request): start_date = request.POST.get('date') end_date = request.POST.get('date1') status = request.POST.getlist('select_status') all_issue_list = … -
i need to show some data in table but those data's are not in a same table ,how to show that data in one table in django
Views.py def meterstatistics(request): varr = Meters_table.objects.all() vark = Meter_Data_table.objects.all() Lastkwh = Meter_Data_table.objects.last() Lasttime = Meter_Data_table.objects.last() d = { 'Lastkwh': Lastkwh, 'Lasttime': Lasttime, 'vark': vark, 'varr': varr } return render(request, 'meterstatistics.html', d) models.py class Meters_table(models.Model): Meter_id = models.AutoField(unique=True, editable=False, primary_key=True) Account_id = models.CharField(max_length=128) Location_id = models.CharField(max_length=150, help_text="(ID of the locations table)") RR_No = models.CharField(max_length=128) Meter_type = models.CharField(max_length=150, help_text="(Industry,Residential & Transformer)") Meter_make = models.CharField(max_length=150) Meter_model = models.CharField(max_length=150) Usage_type = models.CharField( max_length=150, help_text="(Industry,Residential & Transformer)") def __str__(self): return self.Usage_type class Meter_Data_table(models.Model): id = models.AutoField(unique=True, editable=False, primary_key=True) Meter_id = models.CharField(max_length=150) IMEI_Number = models.CharField(max_length=150) KWH = models.CharField(max_length=128) KVAH = models.CharField(max_length=150) PF = models.CharField(max_length=150) BMD = models.CharField(max_length=128) Meter_time_stamp = models.DateTimeField(max_length=150) Receive_time_stamp = models.DateTimeField(max_length=150) def __str__(self): return self.Meter_id HTML <table id="table"> <thead class="thead-light bg-primary"> <tr> <th scope="col">Meter_id</th> <th scope="col">DCU IMEI</th> <th scope="col">RR No</th> <th scope="col">Last KWH</th> <th scope="col">PF</th> <th scope="col">Last Meter Time Stamp</th> <th scope="col">Location</th> <th scope="col">Frequency</th> <th scope="col">Relay</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr> {% for i in vark %} <td>{{i.Meter_id}}</td> <td>{{i.IMEI_Number}}</td> <td>{{i.RR_No}}</td> <td>{{i.KWH }}</td> <td>{{i.PF}}</td> <td>{{i.Meter_time_stamp }}</td> <td></td> <td></td> <td><label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label></td> <td> <a href="{% url 'graph' %}"><i style="font-size: 30px;" class="fa fa-eye" aria-hidden="true"></i> </a> <a href="metertableedit/{{i.Meter_id}}"><i style="font-size: 30px;" class="fa fa-pencil-square-o" aria-hidden="true"></i></a> <!-- <a href="delmetertable/{{i.Meter_id}}"><i style="font-size: 30px;" class="fa fa-trash" aria-hidden="true"></i></a> --> … -
Docker Build sorunu lütfen yardım edin
ERROR: Cannot install -r requirements.txt (line 15), -r requirements.txt (line 21) and python-dateutil==1.5 because these package versions have conflicting dependencies. ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 Buda Benim requirements altgraph==0.17 asgiref==3.3.4 beautifulsoup4==4.9.3 certifi==2020.12.5 cffi==1.14.6 chardet==4.0.0 click==7.1.2 cryptography==3.4.7 Django==3.2.3 dnspython==1.16.0 future==0.18.2 gitdb==4.0.7 GitPython==3.1.18 gunicorn==20.1.0 heroku==0.1.4 html5lib==1.1 idna==2.10 install==1.3.4 mysql-connector==2.2.9 numpy==1.20.2 pandas==1.2.4 pefile==2021.5.24 pycparser==2.20 pyinstaller==4.4 pyinstaller-hooks-contrib==2021.2 pymongo==3.11.4 PyQt5==5.15.4 pyqt5-plugins==5.15.4.2.1.0 PyQt5-Qt5==5.15.2 PyQt5-sip==12.8.1 pyqt5-tools==5.15.4.3.0.3 python-dateutil==1.5 python-dotenv==0.17.1 pytz==2021.1 pywin32-ctypes==0.2.0 qt5-applications==5.15.2.2.1 qt5-tools==5.15.2.1.0.1 requests==2.25.1 selenium==3.141.0 six==1.15.0 smmap==4.0.0 soupsieve==2.2.1 sqlparse==0.4.1 style==1.1.0 typing-extensions==3.10.0.0 update==0.0.1 urllib3==1.26.4 webencodings==0.5.1 gunicorn -
How to integrate Django rest api in cpanel?
Thank You in advance, I am new to programming and I have made my frontend in Reactjs and backend in Django and It is possible to integrate my Django rest and Reactjs frontend in the same Cpanel. Most of the tutorials show the integration of Django with templates but I want to integrate my Django rest API, not with templates. -
Django: Fetch logged in user information from database and show them in html
I've menaged to create a form that allow me to save my website user information in the database. Right now I'd like to create a page where the saved info are showed to my user also. Of course I want my user to be able to see only their own information. This is what I came up with until now, it doesn't wotk and unfortunly I'm not getting any error, just a blanck html page aside for the title. How can I solve this? Thank you all! model.py class Info(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) phone = models.CharField(max_length=10) views.py def show(request): info = Info.objects.all().filter(first_name=request.user) return render(request, 'profile/show.html', {'info': info}) info.html <h1> Profile </h1> </br></br> {% if user.is_authenticated %} {% for info in info %} <li>First Name: {{ info.first_name }}</li> <li>Last Name: {{ info.last_name }}</li> <li>Phone Number: {{ info.phone }}</li> {% endfor %} {% endif %} -
How to print Json data to Django template
{'4': [1, 'Product New', '450.00', '4'], '6': [1, 'Products Hello', '4500.00', '6']} I receive data in my view.py: using products = json.loads(data) After that, i am trying to show each item's in Django templates. 4 and 6 is pro -
error while getting foreignkey id in django
I am new in django.i am trying to make a invoice generator app with django . where an employee inputs the customer id and it takes to the invoice page.in the invoice page the employe can enter a product id and the product and customer info will be added to invoice model object .so i want to add all the products for the same invoice id or want to filter by customer id which will get all the invoices for the customer id here is the code models.py from django.db import models from account.models import Customer from product.models import Product class Invoice(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE, default=1) customers = models.ForeignKey(Customer, on_delete=models.CASCADE, default=4) date = models.DateTimeField(auto_now_add=True) total = models.BigIntegerField(default=0) quantity = models.IntegerField(default=0) views.py def billingform(request): if request.method == "POST": cid = request.POST["customerId"] customer = Customer.objects.get(id=cid) request.session['customerId'] = cid return redirect('invoice') return render(request, 'bform.html') def invoice(request): cid = request.session.get('customerId') customer = Customer.objects.get(id=cid) if request.method == "POST": pd = request.POST["product_id"] qt = int(request.POST["quantity"]) product = Product.objects.get(id=pd) pd_price = int(product.selling_price) total = pd_price*qt pd_name = product.name Invoice.objects.create(products = product, quantity = qt, total=total, customers = customer) cust_id = Invoice.objects.get(id, customers=customer.id) product_name = cust_id.products product_quantity = cust_id.quantity product_total = cust_id.total return render(request, 'invoice.html', { "total":product_total, … -
I am using proxy model, Seller(CustomUser) and Customer(CustomUser), I am getting 'SellerManager' object has no attribute 'normalize_email' error
Error occurs when I create CustomUser by subclassing AbstractUser , but I don't get error when Create customuser by sublassing AbstractBaseUser. Why? class CustomUser(AbstractUser): # making default username to none instead using email as username field username = None email = models.EmailField(_('email address'),unique=True) name = models.CharField(max_length=255) """ Multiple user type without extra fields # 1. Boolean Select Field # option to make if user is seller or customer is_customer = models.BooleanField(default=True) is_seller = models.BooleanField(default=False) # 2 Choice Field with djnago multiselect # type = ( # (1, 'Seller'), # (2, 'Customer') # ) # to select one of two choice, to select multi instal package django-multiselectfield # user_type = models.IntegerField(choices=type, default=1) # 3 Separate class for different rolles and many to many field in user model # usertype = models.ManyToManyField(UserType) """ # Multiple user with extra field # 1 boolean field with class for different role # is_customer = models.BooleanField(default=True) # is_seller = models.BooleanField(default=False) # Proxy model class Types(models.TextChoices): CUSTOMER = "Customer", "CUSTOMER" SELLER = "Seller","SELLER" default_type = Types.CUSTOMER type = models.CharField(_('Type'),max_length=255, choices=Types.choices, default=default_type) # if not code below then taking default value in user model not in proxy in model # The point is that we do not know … -
Hello, Please i am using ajax to display date in django template it is giving me long unformatted date
for example var temp=""+response.messages[key].date+" result: 2021-10-02T09:53:27.896Z how do I make it to show the same as django -- {{date|timesince}} -
How to implement the mouseover product zoom functionality like amazon in slick sync slider? Not working jquery zoom plugins with this slider.possible?
I have done with the default slick sync slider. But cannot implement the jquery zoom plugins inside this slick slider. I want product zoom functionality like amazon..with this slick slider.please anyone tell me, what would be the best option for this.? -
How to restrict Media Folder using Django ? Is it a way?
I tried several tutorials using "FileResponse" to restrict the access to the MediaFolder only on authenticated User... But it does'nt run well online. It ran on localhost, but definitly not online. Is it a way or an App which can restrict the Media folder ?