Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PyCharm (pro) - Django console: ModuleNotFoundError: No module named
I can't use the Django console because I keep having the following error and can't figure it out what to do.. I've tried extensively to search for a solution online but none it seems to work for me.. probably cause I don't know the reason of the problem If I don't use the console the app works just fine without any error but I can't do a proper debugging Here it is the error: /Users/alex/Documents/dev_py/project-crm/venv/bin/python3.10 /Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py --mode=client --port=57445 import sys; print('Python %s on %s' % (sys.version, sys.platform)) import django; print('Django %s' % django.get_version()) sys.path.extend(['/Users/alex/Documents/dev_py/project-crm', '/Users/alex/Documents/dev_py/project-crm/users', '/Users/alex/Documents/dev_py/project-crm/project_crm', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev']) if 'setup' in dir(django): django.setup() import django_manage_shell; django_manage_shell.run("/Users/alex/Documents/dev_py/project-crm") PyDev console: starting. Python 3.10.0 (v3.10.0:b494f5935c, Oct 4 2021, 14:59:20) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin Django 3.2.9 Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 6, in <module> File "/Users/alex/Documents/dev_py/project-crm/venv/lib/python3.10/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/alex/Documents/dev_py/project-crm/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Users/alex/Documents/dev_py/project-crm/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/Users/alex/Documents/dev_py/project-crm/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File … -
Chart.js Setup Using Ajax & Variables
I cannot get my Chart.js to show up on my webpage. I am utilizing two arrays for data/labels and am creating the chart in an onload js function. Tried several different methods from tutorials and other Stack posts. HTML is just <canvas id="piee"></canvas> and I brought chart.min.js into my project and load the script as <script src="{% static "js/chart.min.js" %}"></script> window.onload = function () { console.log("Child: ", document.getElementById("piee")) var ctx = document.getElementById('piee').getContext('2d'); var rep_name = $("#pie1").attr("data-rep-name") var ajax_url = $("#pie1").attr('data-ajax-url') var _data = [] var _labels = [] // Using the core $.ajax() method $.ajax({ // The URL for the request url: ajax_url, // The data to send (will be converted to a query string) data: { name: rep_name }, // Whether this is a POST or GET request type: "POST", // The type of data we expect back dataType: "json", headers: {'X-CSRFToken': csrftoken}, context: this }) // Code to run if the request succeeds (is done); // The response is passed to the function .done(function (json) { if (json.success == 'success') { var newMale = json.malePerc var newFemale = json.femalePerc console.log(newMale, newFemale) _labels.push("male", "female") _data.push(parseFloat(newMale), parseFloat(newFemale)) var newUVB = json.uvbPerc var newSize = json.specSize console.log("data: " + _data) var … -
الجمال واللياقة البدنية [closed]
الجمال واللياقة البدنية يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر -
How do i connect EC2 instance for elastic search in Django?
I'm just trying to add dynamic search as a feature to my application, i used Django Elasticsearch DSL to achieve this https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html, but i'm not able to connect the running postgres EC2 instance. Any leads would be very much appreciated :) Here is the snippet where i have to add the creds - ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } Currently, i'm accessing the EC2 using username, password, of-course Host and Port address. -
I am creating a Web project, Frontend on Reactjs backend on Python Django and use Firebase realtime data base for store data
I Know first create restful api to get data from client side but, dont know the flow of project to make connections for CRUD operations in my project -
Link automatically OneToOneField when creating an objects
Considering this two models in my project: MODEL class Movie(models.Model): user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) title = models.CharField(max_length=250) year = models.DateField(default=auto_now_add=True) def __str__(self): return self.title class List(models.Model): user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) movie = models.OneToOneField(Movie, on_delete=models.CASCADE) [...] I'd like to link the List model to the Movie model when the System objects are created. This is my views file: VIEWS def movie_view(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): [...] List.objects.create( user = request.user.userinformation, list_movies = request.list_movies.list, [...] ) return redirect('add_movie') else: return redirect('index') else: form = FileForm() context = { 'form': form, } return render(request, 'add_movie.html', context) This part list_movies = request.list_movies.list may be the problem since I'm getting this error Django: 'WSGIRequest' object has no attribute error. How can I assign correctly the OneToOneField? -
How can i generate backup codes for two factor authentication
I am try to generate backup codes for the users of my system after they enable two factor authenciation -
Django Find difference in the same model instance
I've been searching around and I don't think I've found my answer quite yet. But I'm looking to be able to find differences in data and have a list of column names that show that. Take for instance I have a model just called my_model that has some columns. object = my_model.objects.get(id=1) # Perform edit some values. old_object = my_model.objects.get(id=1) object.save() # Check for differences model_fields = [field.name for field in my_model._meta.get_fields()] filtered_list = filter(lambda field: getattr(object, field, None) != getattr(old_object, field, None), model_fields) Purpose of this is to notify the user after they make an update on their end to send an email to that user to just give them a reminder that they changed whatever values they changed. -
Protected member accessed from outside the class, Django
I'm trying to condition if a value exist as a property in a model or not. I'm trying to do this Mode()._meta.get_field("id") But I got the following error from pylint Protected member accessed from outside the class Can someone help me please? -
How to assign a default choice value to a user when they sign up in django framework
I am writing a logic where when a users creates and account, i want to automatically assign the free membership to them and i know this should be done in the register view but i don't know why it's not working as expected. I still have to manually go to my admin page and manually assign a value to newly created user and that's not what i really wanted. Models.py class Membership(models.Model): MEMBERSHIP_CHOICES = ( ('Enterprise', 'Enterprise'), # Note that they are all capitalize// ('Team', 'Team'), ('Student', 'Student'), ('Free', 'Free') ) PERIOD_DURATION = ( ('Days', 'Days'), ('Week', 'Week'), ('Months', 'Months'), ) slug = models.SlugField(null=True, blank=True) membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) duration = models.PositiveIntegerField(default=7) duration_period = models.CharField(max_length=100, default='Day', choices=PERIOD_DURATION) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) def __str__(self): return self.membership_type #### User Membership class UserMembership(models.Model): user = models.OneToOneField(User, related_name='user_membership', on_delete=models.CASCADE) membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True) reference_code = models.CharField(max_length=100, default='', blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=UserMembership) def create_subscription(sender, instance, *args, **kwargs): if instance: Subscription.objects.create(user_membership=instance, expires_in=dt.now().date() + timedelta(days=instance.membership.duration)) views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') instance = UserMembership.objects.create(user=obj, membership=get_membership) … -
Multiple Django Apps using one database/model
New to Django...I'm trying to create a project with the following structure: CompanyName <--Project ingredients < -- Application CompanyName supplier <-- Application My issue is that my project is going to use a database/model like the following: suppliers (table) - name - created_by (foreign_key, auth.User) ingredients (table) - name - supplied_by (foreign_key, supplier.name) My question is do I create all the tables in a single models.py or do I break up each table into each application's manage.py? If I use separate models.py, how do you create the suppliers table and then the ingredients table since the ingredients table has a foreign key to suppliers? -
How to create a link that takes me to my DjangoRest api
I started studying Django a few days ago and i want that when I click on a button it takes me to the url of my api. This is my urls from my app: from django.urls import path, include from animes import views from rest_framework import routers router = routers.DefaultRouter() router.register('animes', views.AnimesViewSet, basename='animes') router.register('nota', views.NotasViewSet, basename='notas') urlpatterns = [ ... path('api/', include(router.urls), name='api') ] the problem from my template is here: <a class="botao__link" href="{% url 'api' %}"><button class="botao__botao" type="submit">API</button></a> when i write the url manually i can go to the api without problems , but I can't go clicking the button -
Django ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
I know others have had a similar issues with and getting this same error, but I think my situation is unique. I am running Django 3.1.4 and on my local machine, I can run python manage.py shell with no issue. On the server instance, running what should be the same project, and the same version of Django, I get: Django ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' When trying to run manage.py shell. To make things more cryptic, if I open the shell on my local machine and run: from django.utils.encoding import python_2_unicode_compatible I get the same error. So for some reason when I call manage.py shell from my local machine it doesn't try to import python_2_unicode_compatible, but when I run it from the server it does. I can't find where the discrepancy is. Here is the full stacktrace if that is helpful: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], … -
I can't manage to import and use a javascript function from a .js into a django template. Ideas?
I have a javascript file project_dashboard.js with a few things defined inside of it and an html file where I try to call such function (amont other things). For some reason, I keep getting the error that the function is not defined at HTMLButtonElement.onclick. What drives me crazy is that the first part of the .js is loaded and works (the css is changed if I click on table). So the script is there, but I can't use the function. project_dashboard.js $('table').on('click', 'tr.parent .fa-chevron-down', function(){ $(this).closest('tbody').toggleClass('open'); }); function EnablePositionEdit(position_id) { const checked_events = [] $("#edit_button_____" + position_id).toggle() $("#save_button_____" + position_id).toggle() $("#delete_____" + position_id).toggle() inputs = document.querySelectorAll(".availability_____" + position_id + " input") inputs.forEach(input => { input.removeAttribute("disabled") }) } html {% extends 'action/base.html' %} {% block extrastylesheets %} {% endblock extrastylesheets %} {% block content %} <head> {% load static %} <link rel="stylesheet" href="{% static 'action/css/project_dashboard.css' %}"> <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> </head> ... <div id="edit_button_____{{ position.id }}" style="display: block;"> <button class="btn" style="font-size:10px; color: rgb(59, 89, 152);" onclick = EnablePositionEdit('{{ position.id }}')> <i class="fa fa-pencil"></i> </button> </div> ... {% endblock content %} {% block extrascripts %} <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script> <script type="text/javascript" src="{% static 'action/js/project_dashboard.js' %}"></script> <script> $(document).ready(function() { $('.summernotable').summernote({ toolbar: [], }); }); … -
The intermediary model has no field
i'm newbie in Django world i'm creating a web app to manage products in an online store i created the models for Catergories and Products here are my models : from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=255, unique=True, ) description = models.TextField(max_length=1500) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) categories = models.ManyToManyField('Category', through='CategoryProducts', through_fields=('category_name','product_name')) def __str__(self): return self.name class CategoryProducts(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, ) product = models.ForeignKey(Product, on_delete=models.CASCADE, ) When i try to make migrations , Two errors apear : products.Product.categories: (fields.E338) The intermediary model 'products.CategoryProducts' has no field 'product_name'. HINT: Did you mean one of the following foreign keys to 'Category': category_name? products.Product.categories: (fields.E339) 'CategoryProducts.category_name' is not a foreign key to 'Product'. HINT: Did you mean one of the following foreign keys to 'Product': product? -
Mongodb result and python result difference
when I query in studio3t, I get a response in .net uuid type, and when I query in python, I get UUID Version=1. How can I translate this output in python? mongo response; pyton response; {'_id': UUID('0fc97e3a-8f0c-be4f-a5dc-b166af761afd'), 'Version': 1, -
Django test not created testing database and not work
everyone I created TestCase, but when I put the command "python manage.py test", this test don't work. Can you help me, please? from django.test import TestCase from accounts.models import UserProfile class AccountsTestCase(TestCase): def setUp(self): print('test_setUp') UserProfile.objects.create(email='test@test.com', password='user111333') def get_user(self): user = UserProfile.objects.get(email='test@test.com') -
How to transfer from datatable data to python variable
Good day, guys! does anyone know how I can pass a data from my table to a python variable? Here's my snippet <table class="table table-hover table-dark"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Filename</th> <th scope="col">Date Uploaded</th> </tr> </thead> <tbody> {% for row in files %} <tr> <td>{{ row.0 }}</td> <td>{{ row.1 }}</td> <td>{{ row.3 }}</td> </tr> {% endfor %} For Example, I clicked a table row 2 then it supposedly get the row.1 value then it will transfer to my variable (get_name_from_table) in python. Here's my code in python get_name_from_table = "" return send_file(BytesIO(data_v), attachment_filename= get_name, as_attachment=True) ``` My main activity is to have a download file button, it's so hard for me to find a dynamic download button. :( -
Import "django..." could not be resolved from source Pylance (reportMissingModuleSource)
I created a new virtual environment in my folder "Django 2021", by typing "python -m venv env" in the cmd which was in the same directory as the folder "Django 2021", then I "pip install django" in the already active env, after that I used the command "django-admin startproject devsearch" (also in the venv). Now I had the "env" and "devsearch" subfolders of "Django 2021", then I dragged my "env" folder into my "devsearch" folder. After that I opened my VS Code (IDE) and selected my "devsearch" folder inside "Django 2021" as my workspace. Opened a new terminal (and also activated my venv) and ran the server (python manage.py runserver), everything still worked perfectly. However, after that, I tried coding something (can't remember) but I couldn't test it because django wasn't imported. I hovered my mouse over the problem and it displayed: "Import "django..." could not be resolved from source Pylance (reportMissingModuleSource)". Here is a bit of visual representation: enter image description here (Folders) enter image description here (VS Code) -
Getting MultiValueDictKeyError while checking if a field is empty
I have a regsitration form where a user chooses a plan. I am trying to check that if the field is empty a message should be displayed. The field name is plan. The code is below if password1==password2: if CustomUser.objects.filter(email=email).exists(): messages.info(request, 'User with same email already exists') return redirect('register') elif plan is None: messages.info(request, 'Please select a plan') return redirect('register') else: user=CustomUser.objects.create_user(full_name=full_name.upper(),age=age, phone_no=phone_no, address=address, plan=plan, email=email.lower(), password=password1) user.is_active = False user.save() usr_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = usr_otp) mess = f"Hello, {user.full_name},\n Please enter the otp to validate your email and activate your account. \nYour OTP is {usr_otp} .\n Thanks!" return render(request, 'register.html', {'otp': True, 'user': user}) # return redirect('login') I have tried multiple ways to check whether the plan field is empty or not such as elif plan == ' ' elif not plan elif plan is None elif request.POST['plan'] == ' ' for all these I am getting only one error MultiValueDictKeyError at /account/register 'plan' Request Method: POST Request URL: http://127.0.0.1:8000/account/register Django Version: 3.2.8 Exception Type: MultiValueDictKeyError Exception Value: 'plan' Exception Location: C:\Users\rickb\Envs\virenv\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__ Python Executable: C:\Users\rickb\Envs\virenv\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\rickb\\Envs\\virenv\\jgs', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\rickb\\Envs\\virenv', 'C:\\Users\\rickb\\Envs\\virenv\\lib\\site-packages'] Server time: Mon, … -
import a file from a directory outside Django project
So I am making a UI to manage an ultrasound sensor GPiOs. I have a directory full of sensors' code and then I have a Django project with a django app. I am trying to import a ultrasound.py into views.py to use the main function that gets the distance. The problem is that when I do from Sensores.ultrasonidos import main I get a ModuleNotFoundError: No module named 'Sensores' error. I've seen that I have to add an __init__ file inside the directory. But doesn't work for me. Help is much appreciated. my views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import UltrasonicSensor from Sensores.ultrasonidos import main class IndexView(ListView): template_name = 'index.html' context_object_name = 'sensors' def get_queryset(self): return UltrasonicSensor.objects.order_by('-id')[:5] class SensorDetailView(DetailView): template_name = 'sensor_detail.html' context_object_name = 'sensor' my ultrasound.py: import time from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger def main(): # Grove - Ultrasonic Ranger connected to port D16 sensor = GroveUltrasonicRanger(16) counter = 10 while (counter < 10): distance = sensor.get_distance() distance = (float(distance) / 100) print('{:.4f} m'.format(distance)) if distance < 1: print('Cerca') elif 1 <= distance <= 1.9: print('Medio') else: print('Lejos') time.sleep(1) counter = counter + 1 if __name__ == '__main__': main() -
Select objects from django model based on user input
I have a large django model with about 800 objects and I want to create a view in which the user can select a certain number of those objects to pass to another view for further processing. The fact that there are so many objects of the model makes listing all the objects very unpractical, as the user would have to scroll through 800 objects. In order to address this problem, I want to place an as-you-type search-bar in the top of the view so that the user can type the name of the objects and select them by clicking them. When the objects are selected, they should appear under the search-bar as tags that the user can remove by clicking an "x" next to each one. When the user has made all the required selections, then they should be able to click a button and jump to the next view where those selected objects are accessible. The model I am using can be simplified to: class Song(): song_name = models.CharField(max_length=256) song_author = models.CharField(max_length=256, blank=True) song_content = models.TextField() def __str__(self): return self.song_name class Meta: ordering = ['song_order'] song_order = models.PositiveIntegerField(editable=False, db_index=True) So far I have been able to make a … -
Writing JavaScript function in Django models
I would like to get long, lat variables from my models.py, which looks something like this: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Marker(models.Model): latitude = models.FloatField( validators=[MinValueValidator(-90), MaxValueValidator(90)], ) longitude = models.FloatField( validators=[MinValueValidator(-180), MaxValueValidator(180)], ) And add fetch them to the line myLatLng in JavaScript function initMap() { const myLatLng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: myLatLng, }); new google.maps.Marker({ position: myLatLng, map, title: "Hello World!", }); } the sample code is here: https://developers.google.com/maps/documentation/javascript/examples/marker-simple So I would like to create a marker from my admin page and display it on the map -
TemplateDoesNotExist at / Home.html Exception Type: TemplateDoesNotExist
My Customers urls.py ''' from django import urls from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('', views.Home ,name= 'Home'), path('Hall/', views.Hall ,name= 'Hall'), path('Food_item/', views.Food_item ,name= 'food'), path('About_us/', views.About_us ,name= 'about'), ] ''' My Web_project urls.py ''' from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('customer.urls')), ] ''' Settings.py Templates ''' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Customers View.py ''' from django.http.response import JsonResponse from django.shortcuts import render def Home(request): return render(request, "Home.html", {"title":" Home"}) def Hall(request): return render(request, "Hall.html", {"title": "Hall"}) def Food_item(request): return render(request, "Food_item.html", {"title": "Food_item"}) def About_us(request): return render(request, "About_us.html", {"title": "About_us"}) ''' My cd is web_project>customer>templates>customer>Home.html The error it showing ''' Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Nawaf Bhatti\Desktop\New\web_project\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\rest_framework\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site- packages\django\contrib\admin\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site- packages\django\contrib\auth\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\web_project\customer\templates\Home.html (Source does not exist) ''' -
How to serve premium content base on user subscription in django
Hello guys i hope the way i ask this questions meets the standard way of stackoverflow. I have a projects i'm working on. On this project you need to subscribe a plan (monthly, 3 months or 6 months) to gain access to premium blog post contents and if you are not subscribed but registered, you will only get access to regular blog post contents. I've been able to integrate payment api and also the payment is working, i've also been able to save the payment details on a table in my database. What i need now is how do i filter the user based on their subscription status to serve them the premium or regular contents.Below is my Models and Views. # In models.py class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) username = models.CharField(max_length=200, unique=True, blank=True) email = models.EmailField(max_length=200, unique=True, blank=False) first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) phone_no = models.CharField(max_length=11,validators=[MaxLengthValidator(11)]) profile_picture = models.ImageField(upload_to="images/profile_image",default="default_user_image.jpeg", blank=True, null=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] def __str__(self): return self.username def get_absolute_url(self): return reverse("admin-update-user", kwargs={"pk": self.pk}) class …