Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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")) … -
How to put view.py in a folder? [closed]
I have created a django project and I want to create folder 'faqs' and put my view.py in faqs folder. How do I edit my urlpatterns in urls.py so that when localhost/faqs loads, view.py inside faqs appears on screen. -
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]There is already an object named 'django_content_type' in the database
I installed Django 3.2.6 and I am able to spin up the server using python manage.py runserver however when I want to do migrate through python manage.py migrate i am getting the above error message. How can I solve that? -
django in_bulk multiple fields
Can I create Django in_bulk with multiple fields as the key? for example, I have a model class Sig(models.Model) name = models.CharField(max_length=80) version = models.IntegerField() description = models.CharField(max_length=80) class Meta: constraints = [ models.UniqueConstraint(fields=['name', 'version'], name='AK1') ] Expected output An in_bulk style dictionary with { ('name', 'version') -> Sig object } I'm using Django 3.2 The alternative solution I've found is to create a dictionary using native python instead of django's features which I fear will be slower. -
Can anyone help me on why my clone formset data isnt saved?
Im having the trouble of saving a cloned formset data right now. Now it just saved whatever its at the last row. The cloning works well as shown in the pic. Everything is working well for my web except for this part. To all the pros out there, im a beginner in this, please help me. Would really appreciate it. Stuck at this for 4 days already Assuming all the fields are with text. Those in red circle are not saved and the one in blue circle is saved upon clicking save Here is my code: views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_form = DeviceDetailForm(request.POST) #di_form= DeviceInterfaceForm(request.POST) di_formset = modelformset_factory(DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), extra=1,max_num=3) di_form=di_formset(request.POST) if device_frm.is_valid(): # Create and save the device # new_device here is the newly created Device object new_device = device_frm.save() if dd_form.is_valid(): # Create an unsaved instance of device detail deviceD = dd_form.save(commit=False) # Set the device we just created above as this device detail's device deviceD.DD2DKEY = new_device # If you did not render the hostname for the device detail, set it from the value of new device deviceD.hostname = new_device.hostname deviceD.save() if di_form.is_valid(): deviceI=di_form.save(commit=False) for deviceI in … -
JSONDecodeError at Expecting value: line 1 column 1 (char 0)
I have tried using the methods with recent answers from this platform but am still getting this error. I am reading my data from the database to update my cart. When i click on the up button it just works okay, whenever i click on the remove button(down error i get File "C:\Users\hp\Desktop\UmojaWater\products\views.py", line 177, in updateItem productId = data['productId'] KeyError: 'productId' [20/Aug/2021 05:56:55] "POST /update/ HTTP/1.1" 500 64093 When i check teh json file on browser it brings the jsonencoding type. In general, the encoding is teh one causing all these problems. I can append the number of products but i cannot decrese them. How can i fix this. Here is my view.py code def AllProducts(request): if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.orderitem_set.all() cartitems = order.get_cart_items else: items = [] order = {' get_cart_total': 0, 'get_cart_items': 0} cartitems = order['get_cart_items'] allproducts = Product.objects.all() context = {'allproducts': allproducts, 'cartitems': cartitems} return render(request, "products/AllProducts.html", context) @login_required def userCart(request): if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.orderitem_set.all() cartitems = order.get_cart_items else: items = [] order = {' get_cart_total': 0, 'get_cart_items': 0} cartitems = order['get_cart_items'] context = {'items': items, 'order': … -
Application labels aren't unique, duplicates: staticfiles
I'm having trouble figuring out what I'm duplicating here. I'm trying to migrate my files so I can deploy on Heroku. It says that "staticfiles" is duplicated, but I can't see where the conflict is. Does migration need to be done in order to deploy? or is there something wrong with my database? import dj_database_url import os ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'wiki_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'coding_dojo_final_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'coding_dojo_final_project.wsgi.application' ... WHITENOISE_USE_FINDERS = True ... STATIC_URL = '/static/' db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' -
Django CMS live support chat plugin
I'm building a website using django cms and I need to add a chat to it so that customers can quickly contact tech support. This chat can also be a chatbot that answers some questions and gives the option to contact technical support. Is there a django cms plugin that allows me to do this or can someone recommend me in another way? -
django.core.exceptions.ImproperlyConfigured, need hel
Here's the error message: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'basicsiteApp' from '/Users/msa/trydjango/basicsite/basicsiteApp/init.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I don't have anything written in init.py file because I don't know what I need to write in it so it can work. Here's what I have in views.py: basicsiteApp/views.py from django.shortcuts import render from .forms import SignUpForm from django.contrib import messages def signup(request): if request.method == 'POST' form = SignUpForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Account Created') return render(request, 'signup.html') else: form = SignUpForm() render(request, 'signup.html') -
How to make PDF fillable?
I have links to unfillable PDFs and I want to make them fillable in my python application. I could use Adobe SDK for Python, but does this allow me to automate PDF fillability. I just want to create the fillable fields and display the PDF for users to fill out. I have 10,000 PDFs, so I want to just call the API to make them fillable. -
Stuck two days on this NoReverseMatch thing
Coded in Pycharm Django version 3.2.6 Project hw_v2 app aftersales ... Templates Project URL urlpatterns = [ path('', include(('index.urls', 'index'), namespace='index')), path('admin/', admin.site.urls), path('mkt/', include(('marketing.urls', 'marketing'), namespace='mkt')), path('com/', include(('commercial.urls', 'comercial'), namespace='com')), path('aft/', include(('aftersales.urls', 'aft'), namespace='aft')), path('gen/', include(('general.urls', 'general'), namespace='gen')), path('user/',include(('user.urls','user'),namespace='user')), path('bootstrapTable/',include('bootstrapTable.urls')),] App/aftersales URL: urlpatterns = [ path('', views.aft,name='afti'), path('edit/<int:id>',views.aft_edit,name='aft_edit'), path('view/<int:id>',views.aft_view,name='aft_view'),] Error Page HTML: <td> <a href="{% url 'aft:aft_view' id=itm.id %}" class="lni lni-magnifier"></a> <a href="#" class="lni lni-close"></a> <a href="{% url 'aft:aft_edit' id=itm.id %}" class="fadeIn animated bx bx-edit-alt"></a> </td> Error: NoReverseMatch at /aft/view/1 Reverse for 'aft' not found. 'aft' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/aft/view/1 Django Version: 3.2.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'aft' not found. 'aft' is not a valid view function or pattern name. Exception Location: D:\0 PROJECTS\14 django_website_ali\hw_v2\venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: D:\0 PROJECTS\14 django_website_ali\hw_v2\venv\Scripts\python.exe Python Version: 3.9.2 Python Path: [WindowsPath('D:/0 PROJECTS/14 django_website_ali/hw_v2'), 'D:\\0 PROJECTS\\14 django_website_ali\\hw_v2\\app', 'D:\\0 PROJECTS\\14 django_website_ali\\hw_v2', 'D:\\0 PROJECTS\\14 django_website_ali\\hw_v2', 'D:\\0 PROJECTS\\14 django_website_ali\\hw_v2\\app', 'D:\\Program Files\\JetBrains\\PyCharm ' '2020.1\\plugins\\python\\helpers\\pycharm_display', 'D:\\Program Files\\Python39\\python39.zip', 'D:\\Program Files\\Python39\\DLLs', 'D:\\Program Files\\Python39\\lib', 'D:\\Program Files\\Python39', 'D:\\0 PROJECTS\\14 django_website_ali\\hw_v2\\venv', 'D:\\0 PROJECTS\\14 django_website_ali\\hw_v2\\venv\\lib\\site-packages', 'D:\\Program Files\\JetBrains\\PyCharm ' '2020.1\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Fri, 20 Aug 2021 09:01:56 +0800 I've been stuck here for two days. The error came out … -
is there a solution to the fcntl error when running heroku local web on windows?
I've been trying to run my Django project on heroku local web though, I'm stuck with this error and don't seem to know what to do as a workaround? ModuleNotFoundError: No module named 'fcntl' -
Getting Django to log info to the console and errors to a file
I've made the following logging config: settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": {"()": "django.utils.log.RequireDebugFalse",}, "require_debug_true": {"()": "django.utils.log.RequireDebugTrue",}, }, "formatters": { "django.server": { "()": "django.utils.log.ServerFormatter", "format": "[{server_time}] {message}", "style": "{", } }, "handlers": { "console": {"level": "INFO", "filters": ["require_debug_true"], "class": "logging.StreamHandler",}, "file": { "level": "ERROR", "filters": ["require_debug_false"], "class": "logging.FileHandler", "filename": BASE_DIR / "debug.log", }, "django.server": {"level": "INFO", "class": "logging.StreamHandler", "formatter": "django.server",}, "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, }, "loggers": { "django": {"handlers": ["file", "console"], "level": "INFO",}, "django.server": {"handlers": ["django.server"], "level": "INFO", "propagate": False,}, }, } And just want normal Django console logging alongside file logging when any errors happen. Presently this logs console information just fine and creates a debug.log, but does not output anything to it. This has been tested by just causing a syntax error in the settings file. What is wrong with this config? -
Is there a way how to get a value of a link
I've been working on Django App and I wanna make a function in this. All I wanna do is to redirect a user to a search page with an input of a tag name when the user clicked one of tags of a blog. For example, when a user clicked a tag named 'test', the user would be sent to the search page. And, one of the three inputs has a value 'test', and the result's blogs below is filtered by 'test'. I hope this made sense to u. Below are the codes I believe u need. blog.html {% extends 'base.html' %} {% block title %}|{{ blog.title }}{% endblock %} {% block content %} <div class="header-bar"> <a href="{% url 'latest_blogs' %}">&#8592; 戻る</a> </div> <div class="body-container blog"> <div class="blog-info"> <div class="user-and-date"> <!-- {% if request.user == blog.user %} <a href="{% url 'dashboard' user.id %}">あなた</a>が{{ blog.created }}に作成 {% else %} {{ blog.user }}が{{ blog.created }}に作成 {% endif %} --> <p>{{ blog.user }}</p> <p>{{ blog.created }}</p> </div> <div class="icons"> {% if request.user == blog.user %} <a href="{% url 'blog_update' blog.id %}" class="far fa-edit"></a> {% endif %} </div> </div> <div class="blog-main"> <h2>{{ blog.title }}</h2> <!-- <h3>コンテンツ1</h3> --> <p class="blog-content">{{ blog.content_1 }}</p> {% if blog.content_2 … -
ModuleNotFoundError: No module named 'listings' despite directory being in PATH
I have a file structure like so. remindMe │ │ ├───remind_me_django │ └───listings │ models.py │ __init__.py │ └───scrapy └───scrapy_project │ items.py │ __init__.py │ └───spiders I'm trying to import my models.py file into items.py but to no avail. When attempting to import into items.py, I get a ModuleNotFound error. Other suggestions say to add my directory to my path but that's been unsuccessful so far as well. sys.path.append("C:\\Users\\Denze\\Projects\\remindMe\\remind_me_django\\listings") from listings.models import Product I've also tried: from remind_me_django.listings import Product The funny thing is with this import, if I right click on the import within VSCODE and go to it's definition, it opens up that modules init file, so VSCODE knows what I'm referencing but Python does not? -
How to create a custom Django user model in an existing project (still early on in the project)
I'm trying to create a custom Django user model as I am using Auth0 for my user authentication but still want to store the user information for Auth0 within my Django project and database. I already have Django project that I ran migrations on so I can't make a custom User model from the beginning if I were to do it at the start of a project. At being said though, I'm still really earlier in the project. I only have 1 user (being the superuser) and the other models I have don't have any references to any user models. I'm still new to Django and I'm a bit confused on how to go about creating a custom Django user model in this certain situation and any help would be really appreciated, thank you.