Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
running php file with pycharm and redis server
I am working on a django project which requires to run 2 php files. One of the file must have access to the redis database that I configured in docker-compose file. So, how do I run these php files and map redis database. I am using ubuntu os. Any Ideas? Thanks :) -
How can I allow access to my Django web server to someone on the same VPN network?
I have a Django app that I'm running with python manage.py runserver 0.0.0.0:8000 I'm also connected to a corporate VPN for work. I can access this app by going to localhost:8000/admin or 192.x.x.x:8000/admin in my browser, that's fine. What I want to do is provide access to this Django app to my coworker, who is connected to the same VPN as me. How can I do this? EDIT: also want to note I have the django settings file with DEBUG = False ALLOWED_HOSTS = ['*'] -
Display SQL table with primary key pair in Django admin
How can I display an SQL table that has a primary key pair as an unmanaged table in Django admin? More details: I have a Django project running in docker that is sharing a Postgresql DB with another program in another docker container. I want to use Django Admin to display all database tables, including the ones that were created outside of Django. This works fine using the Meta "db_table" and "managed" attributes. However, when I have an SQL table with two primary keys, Django admin gives me an error: column user_settings.id does not exist These are the tables: SQL: CREATE TABLE user_settings( user_id INT, setting_id INT, value INT, PRIMARY KEY (user_id, setting_id) ); Django: class UserSettings(models.Model): user_id = models.IntegerField() setting_id = models.IntegerField() value = models.IntegerField() class Meta: managed = False db_table = 'user_settings' -
Error with setting up minIO in docker-compose: <ERROR> Unable to initialize new alias from the provided credentials
I have trouble with setting up minIO in my docker-compose. I found this problem on several websites and tried to make it work. But I failed :D Anyway, if anyone is able to help me I will call him my personal hero. Here is my code: # docker-compose.yml minio: container_name: minio image: minio/minio ports: - "9000:9000" volumes: - ./minio-data:/data env_file: - app/.env command: server /minio-data mc: image: minio/mc depends_on: - minio entrypoint: > /bin/sh -c " until (/usr/bin/mc config host add myminio http://minio:9000 access-key secret-key) do echo '...waiting...' && sleep 1; done; /usr/bin/mc mb myminio/local-bucket/; /usr/bin/mc policy set download myminio/local-bucket; exit 0; " # settings.py DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = env.str("MINIO_ACCESS_KEY", default='access-key') AWS_SECRET_ACCESS_KEY = env.str("MINIO_SECRET_KEY", default='secret-key') AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", default='local-bucket') MINIO_STORAGE_USE_HTTPS = False if DEBUG: AWS_S3_ENDPOINT_URL = env.str("AWS_S3_ENDPOINT_URL", default='http://minio:9000') # .env MINIO_ACCESS_KEY=access-key MINIO_SECRET_KEY=secret-key AWS_STORAGE_BUCKET_NAME=local-bucket AWS_S3_ENDPOINT_URL=http://minio:9000 And thats my console logs: -
Django manual forms
I am trying to get my head around using manual forms. When I have in my forms.py checked that fields name and email is readonly class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'email', 'body'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs['readonly'] = True self.fields['email'].widget.attrs['readonly'] = True And in the html <form action="." method="post"> {% csrf_token %} <div class="comment-area hide" id="comment-area"> <div class="mb-4"> <label for="{{ form.name.id_for_label }}" class="form-label">{{ form.name.label }}: </label> <input class="input is-medium" name="{{ form.name.html_name }}" type="text" class="form-control" id="{{ form.name.id_for_label }}" placeholder="{{ request.user.username }}" readonly> </div> <div class="mb-4"> <label for="{{ form.email.id_for_label }}" class="form-label">{{ form.email.label }}: </label> <input class="input is-medium" name="{{ form.email.html_name }}" type="email" class="form-control" id="{{ form.email.id_for_label }}" placeholder="{{ request.user.email }}" readonly> </div> <div class="mb-4"> <label for="{{ form.body.id_for_label }}" class="form-label">{{ form.body.label }}: </label> <textarea class="textarea is-small" name="{{ form.body.html_name }}" class="form-control" id="{{ form.body.id_for_label }}"> </textarea> </div> <div class="field"> <div class="control"> <button class="button is-success">Submit comment</button> </div> </div> </div> </form> But still when submitting without name and email, got error on missing both name and email. If anyone can help, much appreciated -
Database error in django+mongodb objects.fiter with boolean field
I am using djongo library to handle mongodb, but still getting database error while filtering queryset using a boolean field. Error: No exception message supplied, django.db.utils.DatabaseError from django.contrib.auth import get_user_model User = get_user_model() users = User.objects.filter(isVerified=True) -
How to create a Django dropdown form using forms.py without a model?
I need to create a simple presentation filter for a Django webpage. Since it's discarded without need for storage, I do not need to use Model overhead. Here is my relevant views.py code: @login_required() def cards(request): # form = CountryForm() 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 sort_name = [] sort_name.append("Alphabetic Order") sort_name.append("Most Popular") sort_name.append("Least Popular") sort_name.append("Highest Win Rate") sort_name.append("Lowest Win Rate") form = cardStatsForm(filter_name, sort_name) Given that my values may change dynamically, I am trying to establish the cardStatsForm() object without initially knowing the values that will occur when publishing the page to the end user. The following code resides within forms.py: from django import forms class cardStatsForm(forms.Form): def __init__(self, filter_opts, sortOrder, *args, **kwargs): super(cardStatsForm, self).__init__(*args, **kwargs) self.fields['filts'].choices = filter_opts self.fields['sorts'].choices = sortOrder filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True) sorts = forms.Select(choices=()) Unfortunately I haven't had to worry about the html side yet since I keep getting the following error with respect to … -
Getting Field 'None' expected a number but got 'update'. when using UpdateView in Django
I am using UpdateView for my update page, but I get this error: Field 'None' expected a number but got 'update'. my urls.py looks like this: path('post/<pk>/update/', PostUpdateView.as_view(), name='post_update'), Everything works fine if I change my update URL to anything other than "post". For example, this works fine: path('abcxyz/<pk>/update/', PostUpdateView.as_view(), name='post_update'), I would like to use the word "post" in URL, because i also use it in the other URLs and they work just fine (except for delete view, which gives me the same error). Is there any way to fix this error without changing the URL? Note: It has worked before, but it broke at some point when I was trying to use django-PWA. I'm not sure if this is related though. Thank you for your help! -
numpy warning with django 4 - 'numpy.float64'> type is zero
I just updated numpy and I get the following warning with Django. How can I fix it? /usr/local/lib/python3.9/site-packages/numpy/core/getlimits.py:89: UserWarning: The value of the smallest subnormal for <class 'numpy.float64'> type is zero. -
Django CustomUser Model - Email Adress already taken
I tried to do a CustomUser Manager in Django. When i try to login or register a new user with my form I always get errors like: "Email adress already taken" or "Passwords don't match". I tried different solutions here, but nothing worked for me so far. I'm new to coding so please don't judge me :) models.py from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) class MyUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.is_staff = True user.save() return user class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email Adresse'), unique=True) user_name = models.CharField(max_length=20, unique=True) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=50, blank=False) birthdate = models.DateField(null=True, blank=False) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) sex = models.CharField(max_length=1, default='K', choices=Sex.SEX_CHOICES,) vacc = models.CharField(max_length=1, default='K', choices=Vacc.VACC_CHOICES,) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email I always get the error: "Email … -
Best way to design API with Django rest framework working asynchronously
I want to build an API that will get called by different bots to do a variety of stuff. Since I already know that my main API will get a lot of requests, I want it to be asynchronously. I saw that we can use asyncio with django rest framework but is it a good idea ? Is there another way or maybe I should use Flask ? I'm fairly new to the API world so thanks in advance ! PS: I've already started working on it but I'm having a hard time finding how I can make my "post" function async -
Django 4.0 and celery no such file or directory
I updated Django to 4.0 and now I get the following error, can someone please help. The celery version is 5.2.1 The error I get is Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/celery/result.py", line 329, in throw self.on_ready.throw(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/vine/promises.py", line 234, in throw reraise(type(exc), exc, tb) File "/usr/local/lib/python3.10/site-packages/vine/utils.py", line 30, in reraise raise value FileNotFoundError: [Errno 2] No such file or directory [06/Jan/2022 18:15:54] "GET /api/task/37e0fe4d-d149-42c3-81e6-7549d294b3fe/ HTTP/1.1" 500 16113 -
upgrading bootstrap changed form styling
I have Django forms with crispy forms. I upgraded from bootstrap 4.0 to the latest version 5.1.3. I correct most of the changes but I cant figure out why the form styling has changed. You can see the spacing between the form fields has greatly changed. How do I go about correcting this to look like bootstrap 4.0 code: <div class="loginout-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="login-register-btn" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small> <div class="inline"> <small class="text-muted"> Forgot Password? <a class="ml-2" href="{% url 'reset_password' %}">Reset Password</a> </small> </div> </div> </div> -
Can't get JSON data on console
Trying to console.log the data before rendering it on page but I keep getting 404 not found or not attributeName 'Porfile' don't have username as an attribute. I'm a noob when it comes to JSON, I've only started messing around with it recently, please help it's for an assignment JS: $.ajax({ type: 'GET', url: 'my-profile-json/', success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); Urls: from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views from .views import ( post_view_json, profile_test_view, MyProfileView, MyProfileData, ) urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("test", profile_test_view, name="test"), path("my/", MyProfileView.as_view(), name="my-profile-view"), path("my-profile-json/", MyProfileData.as_view(), name="my-profile-json"), # endpoints path("posts-json/", post_view_json, name="posts-view-json") ] Views from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.shortcuts import render from django.urls import reverse from django.core import serializers from .models import User, Post, Profile from django.views.generic import TemplateView, View class MyProfileData(View): def get(self, *args, **kwargs): profile = Profile.objects.get(user=self.request.user) qs = profile.get_proposals_for_following() profiles_to_follow_list = [] for user in qs: p = Profile.objects.get(user__username=user.username) profile_item = { 'id': p.id, 'user': p.username, 'avatar': p.avatar.url, } profiles_to_follow_list.append(profile_item) return JsonResponse({'pf_data': profiles_to_follow_list}) class … -
Django Pandas Dataframe with display with neasted list
i still newbie on django, i would like this ask the table how to create pandas with pivot table with neasted list. data_list = [{'id': '1', 'date':2022-1-10 'car': 'toyota', 'car_material': {'ST1230': {'name': 'Steel', 'qty': 13}, 'MT1239': {'name': 'PVC', 'qty': 8}}}] pivot = pd.DataFrame(data_list) OutPut | id | date | car | car_material | |----|-----------|--------|--------------------------------------------------------------------------------| | 1 | 2022-1-10 | toyota | {'ST1230': {'name': 'Steel', 'qty': 13}, 'MT1239': {'name': 'PVC', 'qty': 8}}} | How to make it like this ? Final Result Output | id | date | car | car_material | name | qty | |----|-----------|--------|--------------|-------|-----| | 1 | 2022-1-10 | toyota | | | | | | | | ST1230 | stell | 13 | | | | | Mt1239 | PVC | 13 |