Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
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 …