Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'base'
every time I try to run my program using python manage.py runserver the same error comes up. I have already added my Django app in my settings.py. this error first came up after starting my Django project and installing my Django app. The error: > Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\apps\config.py", line 211, in create mod = import_module(mod_path) File "C:\Program Files\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked … -
what technology to use to make a chatapp?
what technologies would be best to add a chat app to your website? Like, I see a live customer support chat box on many websites. I think php and ajax are a common way of doing it. I also think django could be commonly used. However, I was wondering if there's a better or "best" way to do this sort of thing? Such as using javascript like next.js, reactjs, and preactjs. There's twilio and plivo. What's a modern and like high quality approach to accomplish adding a live chat pop-up window to a website? My other related inquiry is what to use for creating a website like omegle or a random chat website? -
How to properly connect models in Django?
In my project I want to have global database of ingredients. I also want for each User to have a possibility to add a ingredient to his own Fridge model but with additional field "numOf". I've stumbled upon errors with PATCH request and im thinking that my database is wrongly connected. Does anyone maybe have a better idea how to arrange my models? Ingredient models class Ingredient(models.Model): name = models.CharField(max_length=100) class UserIngredient(models.Model): ingredient = models.OneToOneField(Ingredient, unique=True, on_delete=models.CASCADE) numOf = models.IntegerField(default=1) Fridge model class Fridge(models.Model): owner = models.OneToOneField(User, related_name='fridge', on_delete=models.CASCADE) ingredients = models.ManyToManyField(UserIngredient, blank=True) def __str__(self): return self.owner.username + "'s Fridge" def save(self, *args, **kwargs): super().save(*args, **kwargs) For example, let 1st user have 2 Apples, 2nd 3 Apples and 3rd 4 Apples in their Fridge. Then in UserIngredient table I have 3 records: Apple 2, Apple 3, Apple 4 which all point to a single Apple Ingredient. How can I avoid this redundancy and just point to a Ingredient instance? -
GDAL path issues in macOSX High Sierra
Had GDAL installed and working on my machine (macOS running 10.13.6) for a Django project running python 3.6.5. Didn't have any issues for 2+ years and haven't changed anything (to my knowledge), but now running into an issue when I try to execute a manage.py command where it will err out with OSError: dlopen(libgdal.so, 6): image not found Trace: Traceback (most recent call last): File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/options.py", line 214, … -
How to integrate any company SSO to my Django app?
I have an app for businesses and one of their main requests is to integrate their SSO (some uses Okta, others use Azure). Currently we use python-social-core, but to add a new company we have to modify code. Do you know a better and simpler way to do this? Like a library that allows me to generate the SAML2.0 url or the redirect link of OIDC, without messing with ENV variables on my app. -
Django form not saving to database via ModelForm
I am trying to add my form to the database using the ModelForm but it's not going through or even printing the form in the view, i have also tried doing each field alone in the view via cleaned data still nothing inserted in the database my view.py def index(request): component = Component.objects.all() form = ComponentModelForm() if request == 'POST': form = ComponentModelForm(request.POST) print(form) if form.is_valid(): form.save() return redirect('/maintenance') else: form = ComponentModelForm() context = { 'components': component, 'form':ComponentModelForm(), } return render(request, 'maintenance/index.html', context) models.py class Component(MPTTModel): name = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) model = models.CharField(max_length=100) serial_number = models.CharField(max_length=255) price = models.IntegerField() note = models.TextField() parent = TreeForeignKey("self", verbose_name=( "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE) def __str__(self): return f"{self.id}, {self.name}" forms.py class ComponentModelForm(forms.ModelForm): class Meta: model = Component fields = ("name", "manufacturer", "model", "serial_number", "price", "note", "parent",) the template: <div> <form method='POST' action=''> {% csrf_token %} {{form.as_p}} <input type="submit" value='Create'/> </form> </div> -
How to correctly design a django database?
I have been learning Django recently, before, I used to design the ER models and all that stuff by myself, although I'm not an expert on databases. I have some questions that I couldn't find anywhere. In terms of designing the database, does a Django developer use only the UML diagrams related to the models or does he/she designs the ER models and then the tables? If the developer only uses the UML diagrams, is database normalization necessary or even applicable in this case? In my ignorance I opted to design the models as UML because I like to have diagrams and it seemed appropriate to me. Is this the right approach? UML diagram of django models Thank you. -
my Django website style broken after upload on shared hosting
My site can't locating where it's static and media file after upload on shared hosting. Here is my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = '/home/project32/rootfolder/media/' STATIC_ROOT = '/home/project32/rootfolder/static/' ** root urls.py** urlpatterns = [ path('admin/', admin.site.urls), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) where I am doing mistake? why my web site not location the static folder of my shared hosing ? I also run python manage.py collectstatic -
How can I stream a local video in a Django view, in loop?
I am streaming a local video in a Django Response using StreamingHttpResponse and this code, but I am not sure how can I loop the video so it replays after finishing. -
Django APIView data format from AJAX
I was trying to send an array of objects in views.py using APIView to insert multiple rows in 1 post request. This is my JavaScript data format: const data = { group_designation: [ {id: 1}, {id: 2}, {id: 3}, ] } I run an insomnia app and it only accepts this kind of format: { "group_designation": [ {"id": 1}, {"id": 2}, ] } However, if I send a post request using the javascript format stated above, it gives me a bad request error(400). This is the payload in network tab: group_designation[0][id]: 1 group_designation[1][id]: 2 group_designation[2][id]: 3 In Django, this is the request.data result: <QueryDict: { 'group_designation[0][id]': ['1'], 'group_designation[1][id]': ['2'], 'group_designation[2][id]': ['3'] }> My code in Django: def post(self, request): temp_objects = [] new_data_format = {'group_designation': temp_objects} serializer = GroupSerializer(data=new_data_format, many=True) if serializer.is_valid(raise_exception=True): group_data_saved = serializer.save() return Response({ "success": "success!!!" }) I was just trying to rewrite the data format so it will be saved but no luck trying. Please help. Thank you! -
Use pipenv with django heroku
So I began to code a project with python, and I was using a tutorial that told me to use a pip environment as my virtual environment. A problem arose, however, when I performed the git push heroku master command. It could not find the package django-heroku! I was confused, because when I ran python manage.py runserver, the server on my computer ran. I later realized that the problem was that the pip environment was located in a .virtualenvs folder that was outside of the folder I was pushing to heroku. I then changed to a python environment, which was located in the directory I was pushing to heroku. The problem was solved! The virtual environment, and consequently the installed packages, were inside the directory being pushed to git, and I could use them in my website! But the question still remains: can you use a pip environment for a django project being pushed to git? Thanks! -
How to display error when using is_active for Login
I set a user.is_active to false so they can't login. user.is_active=False user.save() I would like to override the login section to show that the account has been disabled. Currently it shows on disabled accounts. Please enter a correct username and password. Note that both fields may be case-sensitive. I am using the auth login path('accounts/', include('django.contrib.auth.urls')), with a simple template {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Log In</h2> <form method="POST" action="."enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> <button><a href="{% url 'signup' %}">Sign up</a></button> </form> {% endblock %} -
Manager isn't available; 'auth.User' has been swapped for 'reg.User'
I can't seem to find a solution for the error I'm getting when trying to save a user. I wish to save different users. I have searched for previuosly answered questions with the similar problems, and have tried to use get_user_model but the error still clings. Kindly Check my code and guide to the solution. Manager isn't available; 'auth.User' has been swapped for 'reg.User' Here is my Models file from enum import unique from django.db import models from django.db.models.fields import DateField from django.db.models.fields.related import OneToOneField from django.urls import reverse from django.contrib.auth.models import AbstractUser, BaseUserManager, PermissionsMixin import datetime import os from django.db.models.deletion import CASCADE, SET_NULL class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Email Address Required') email = self.normalize_email(email) user = self.model(username=username, email=email, password=password) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser): is_agent = models.BooleanField(default=False) is_coordinator = models.BooleanField(default=False) is_regional_director = models.BooleanField(default=False) is_national_director = models.BooleanField(default=False) objects = CustomUserManager() class National_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) objects = CustomUserManager() #Views from django.shortcuts import render,redirect from django.http import HttpResponse from django.views.generic import CreateView … -
How to prevent Django save action to avoid repetitive DB calls on already existing data
My current code for saving articles saves new articles and prints 'The Post Already Exists!' if a duplicate is found, but it's still making DB calls and so now I have ID gaps in my articles table because of the false saves caused by duplicate articles not being saved. How can I improve my code to prevent the save action if a duplicate is found to preserve consistency in my article IDs? if not Posts.objects.filter(title=post_title, slug=post_slug).exists(): post = Posts( title = post_title, link = post_link, summary = post_summary, image_url = image_link, slug = post_slug, pub_date = date_published, guid = item.guid, feed_title = channel_feed_title, feed_link = channel_feed_link, feed_description = channel_feed_desc, source_id = selected_source_id, category_id = selected_category_id ) post.save() for i in range(len(article_list)): post_tags = post.tags.add(article_list[i]) else: print("The Post Already Exists! Skipping...") I keeping getting such errors: django.db.utils.IntegrityError: duplicate key value violates unique constraint "Posts_posts_slug_key" DETAIL: Key (slug)=() already exists. -
Django POST is missing positional argument
I'm bypassing the use of a model to get basic filter responses for presentation purposes from the user. Accordingly, I've defined a cardsStatsForm class as below: forms.py from django import forms class cardStatsForm(forms.Form): def __init__(self, filterList, sortList, *args, **kwargs): super(cardStatsForm, self).__init__(*args, **kwargs) self.fields['filts'].choices = filterList self.fields['filts'].label = "Select player rankings for inclusion in statistics:" self.fields['sorts'].choices = sortList self.fields['sorts'].label = "Choose a sort order:" filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True) sorts = forms.ChoiceField(choices=(), required=True) Unfortunately, when I retrieve the POST command, I am getting a positional argument error. I am confused, however, because I thought the point of the POST is to retrieve values. So why does "post-POST" code typically run the class instance? If i were to submit a positional value, would it not be overwritten by this statement? Isn't request.POST a form of "self" statement? views.py @login_required() def cards(request): f_name = STAT_FILES / 'csv/segment_summary_quart.csv' # pathname = os.path.abspath(os.path.dirname(__file__)) df = pd.read_csv(f_name, index_col=None) pl_name = STAT_FILES / 'pickles/lbounds' pu_name = STAT_FILES / 'pickles/ubounds' lbounds = pickle.load(open(pl_name, "rb")) ubounds = pickle.load(open(pu_name, "rb")) filter_name = [] i = 0 max_i = len(ubounds) while i < max_i: filter_name.append(f'Personal best trophy range: {str(int(lbounds[i])).rjust(4," ")}-{str(int(ubounds[i])).rjust(4," ")}') i += 1 filter_id = range(len(filter_name)) filter_list = list(zip(filter_id, filter_name)) … -
Django " ImproperlyConfigured:"
I have created a blog with django by following some book. The django website works but the terminal keeps on showing this message if i try to interpret the code on spyder(setting.py, models.py) ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings the solution which was given for this was: set DJANGO_SETTINGS_MODULE=mysite.settings as in the documentation for django. However if i stop the server and restart it after running the code i am still getting the same error. Could you please advise what setting it is referring to which are not configured? This is perticularly odd because it prints out the same error message if I run this help(models.DateTimeField) -
my background image property cant function in my Django project yet the static files are functioning and my other CSS properties are also functioning
kindly need your help.Ive connected my Django static files(CSS and images) and basically the html and CSS are connected very well, however there is only one CSS property that's not working and that is "background-image".ive tried giving the website a background image but it cant display my image inspite of other CSS properties functioning very well.what do you think may be the problem? -
Mysql query of 200000 rows just crashes before showing on the view
I have a project with this stack: Python, Django, Django REST-Framework, MySQL, Angular. Currently I have an app that has a functionality to list some rows, when you try to list them on the view, they should be shown by pages of 20 rows each, loading in a single query 200000 rows but showing nothing because it crashes. I want to know if I have to optimize my code or do something with the DB. -
Please how can I collect data from multiple forms, having multiple templates using one view
I have all my forms in a list and my templates in a dictionary. I want to collect information from the forms without having to create a model for each form and also without creating separate views for each form. FORMS = [ ('step_1', PersonalDetails()), ('step_2', Summary()), ('step_3', Employment()), ('step_4', Education()), ('step_5', Social()), ('step_6', Skill()) ] form_list = [item[1] for item in FORMS] TEMPLATES = { 'step_1': 'form_1.html', 'step_2': 'form_2.html', 'step_3': 'form_3.html', 'step_4': 'form_4.html', 'step_5': 'form_5.html', 'step_6': 'form_6.html', } -
NoReverseMatch at /user/admin/
I am trying to make a site to post photos. Where you can follow and unfollow people. here's the views of follow, unfollow and see-use-profile def seeUserProfile(request,username): user= User.objects.get(username=username) already_followed = Follow.objects.filter(follower=request.user,following=user) print(already_followed) if user == request.user: return redirect('profile') return render(request,'App_post/view_profile.html',context={'user':user,'already_followed':already_followed}) @login_required def follow(request,username): following_user = User.objects.get(username=username) print(following_user) follower_user = request.user print(follower_user) already_followed = Follow.objects.filter(follower=follower_user, following=following_user) print(already_followed) if not already_followed: followed_user = Follow(follower=follower_user,following=following_user) followed_user.save() return redirect('profile',kwargs={'username':username}) @login_required def unfollow(request,username): following_user=User.objects.get(username=username) follower_user=request.user already_followed= Follow.objects.filter(follwer=follower_user,following=following_user) already_followed.delete() return redirect('profile',kwargs={'username':username}) models.py of following class Follow(models.Model): follower=models.ForeignKey(User,on_delete=models.CASCADE,related_name='follower') following= models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') created_date=models.DateTimeField(auto_now_add=True) urls.py from django.urls import path from .import views urlpatterns = [ path('',views.home,name="home"), path('profile/',views.profile,name="profile"), path('user/<username>/',views.seeUserProfile,name="viewprofile"), path('follow/<username>/',views.follow,name="follow"), path('unfollow/<usename>/',views.unfollow,name='unfollow') ] html django tamplates code to show follow/unfollow {% if not already_followed %} <a href="{% url 'follow' username=user.username %}" class="btn btn-primary">Follow</a> {% else %} <a href="{% url 'unfollow' username=user.username %}" class="btn btn-primary">Unfollow</a> {% endif %} But the problem is when i follow a person it does not redirect me to his profile instead it shows me NoReverseMatch at /user/admin/ Reverse for 'unfollow' with keyword arguments '{'username': 'admin'}' not found. 1 pattern(s) tried: ['unfollow/(?P<usename>[^/]+)/$'] Request Method: GET Request URL: http://localhost:8000/user/admin/ Django Version: 3.2.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'unfollow' with keyword arguments '{'username': 'admin'}' not found. 1 pattern(s) … -
Djangi database storage issue
So I am running a particular code block in threads(5), and in the code been executed by the threads data are been saved to the database. e.g. link = AccountLinkModel.objects.create(account=account) if I print the value of "link" object and any field from the AccountLinkModel model, they print successfully, which means the data was created, but eventually, the record of some was not found in the Database, only few were recorded in the database. Any advice on what might cause this? -
How to mock a function taking in csv.reader(csv_file, delimiter=",")
I have a function that reads headers and rows from csv.reader(csv_file, delimiter=","), how can I create a mock csv.reader(csv_file, delimiter=",") to pass to the function with headers and rows to read without creating new files in the app directory Here is the function def upload_loan_application(data): # skip headers row headers = next(data) for row in data: # read the row data here and here is how it is called with open(obj.file.path, "r") as csv_file: data = csv.reader(csv_file, delimiter=",") upload_loan_application(data) -
using django-allauth + dj-rest-auth - Facebook don't appear in Admin panel
I've started a fresh Django project and I'm using django-allauth + dj-rest-auth and according to this doc: https://dj-rest-auth.readthedocs.io/en/latest/installation.html#social-authentication-optional I just need to add this on my settings.py file: INSTALLED_APPS = ( ..., 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth' ..., 'django.contrib.sites', 'allauth', 'allauth.account', 'dj_rest_auth.registration', ..., 'allauth.socialaccount', 'allauth.socialaccount.providers.goodgle', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.twitter', ) SITE_ID = 1 Now on my admin pannel I see "Social Network" and when I click on Provider, I can see only Twitter and Google but no Facebook at all. I tried to uninstall django-allauth and dj-rest-auth. Tried even to install them with previous versions and still the same. Everyone who uses those packages on YouTube (or blogs) and wanna use Facebook does exactly like me and they got "Facebook" in the list. Something is wrong but I don't know even why. -
How do I display form instance values outside of input forms?
from django.db import models from django import forms class Author(models.Model): name = models.CharField(max_length=254, primary_key=True) class Patron(models.Model): name = models.CharField(max_length=254, primary_key=True) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.PROTECT) title = models.CharField(max_length=254) isbn = models.CharField(max_length=254, primary_key=True) checked_out_to = models.ForeignKey(Patron, null=True, default=None, on_delete=models.CASCADE) class BookInfoForm(forms.ModelForm): class Meta: model = Book fields = '__all__' Consider the code snippet above. I'm trying to create a form that displays the provided information from the given model instance, but only allows for the checked_out_to field to be editted. The other fields should not display as input fields. The readonly, hidden, and disabled attributes are not what I'm looking for. Thank you for reading my question :) EDIT: I will be looking to expand this into a formset as well. -
convert InMemoryUploadedFile file object to zip object
Model dummy_doc = models.FileField() I have a object of type <django.core.fiels.uploadedfile.InMemoryUploadedFile> this object can have file type (.csv, .png, .pdf) print(type(file_object)) >> <django.core.fiels.uploadedfile.InMemoryUploadedFile> print(file_object.__dict__) >> {'file': <_io.BytesIO object at 0x1xsdsdsdummy>, '_name': 'dummy.csv', '_size': 3, 'content_type': 'text/csv', 'charset': None, 'content_type_extra': {}, 'field_name': 'dummy_doc'} i want a new InMemoryUploadedFile object with content_type as zip for any file type