Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check routes on template?
Does anyone know how to check if a template is being accessed through a url route with the django template language? Here is my situation: There's this template article.html, that shows all posts of a blog when accessed through blog-home url route, and that also shows only posts of a given user through user-posts url route. This template works like that because what defines which posts will be shown are the classes in views.py. That being said, here is what I tried to do: (I know its wrong) {% if url == 'user-posts' %} "Some HTML h1 tag I want do be shown only when this template is accessed via 'user-posts' url" {% endif %} How would be the correct way, if there's any, to write this if statement? -
how to save CustomUser model to another model data
here is my code at users/admin.py, from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from store.models import Customer from .forms import CustomUserCreationForm, CustomUserChangeForm CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username',] admin.site.register(CustomUser, CustomUserAdmin) I have table on store/models.py , class Customer(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True,unique=True) #name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) def __str__(self): return self.user.username Now can anyone please suggest me how to create a customer instances in user/admins.py or save data to customer table. -
how to take input from one page and send them into another page in django
I'm fairly new at this. I'm trying to build a report page in iframe according to user requirement user can create report with src, width and height ...and i successfully done this...i am able to create the report now i want this created report name will be show in the dropdown menu and when the user click on report name then user can see the report and the name of the report will add on dynamically in the dropdown.... i'm waiting for response ..here i'm going to share the code what i have done ... i would say one more thing i don't want to add these data (Src,width ,hesight,name of the report) in the data base ...is that possible to create report and get the same report when i will click on the report name. index.html <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Reports<span class="caret"></span></a> <ul class="dropdown-menu"> <li class="dropdown-header">Reports</li> <li> <div class="buttons pull-right"> <a href="{% url 'report:reporttest' %}" class="btn btn-xs btn-success" title="Add"><i class="fa fa-plus"></i></a> </div> <a href="{% url 'report:reporttwo' %}">Report one</a> </li> {% if name %} <li> <a href="{% url 'report:add' %}">{{name}}</a> </li> {% endif %} </ul> </li> reportform.html <form action = "add" method= "post" enctype="multipart/form-data" class="form form-horizontal"> … -
Git commit from a bisect
I have only ever used 'git add .' for this project, but somewhere along the line I started getting the strange "modified content, untracked content" error on one of my subdirectories (called users). Other stackoverflow answers didn't work for me. I used checkout to go back through previous commits, but the buggy/untracked subdirectory didn't change with the rest of the directory. I ended up making manual changes to it and then running 'git checkout master' to make sure everything else was back where it started. Git is saying that I'm bisecting, and it won't let me commit. I looked over stackoverflow answers, and tried some of the following commands: 'git pull': There is no tracking information for the current branch. Please specify which branch you want to merge with. 'git pull origin master': fatal: 'origin' does not appear to be a git repository 'git branch --set-upstream-to=origin/master master' error: the requested upstream branch 'origin/master' does not exist hint: hint: If you are planning on basing your work on an upstream hint: branch that already exists at the remote, you may need to hint: run "git fetch" to retrieve it. hint: hint: If you are planning to push out a new local … -
Sign Up Form Submission Producing a Data Breach pop up in Chrome
I built a django app, but I've run into an issue with my signup form. Whenever a user submits the form on chrome a warning pops up referencing a data breach. It's the same warning referenced here. I can see that that the warning is generated by chrome whenever the user's data is exposed by the web app. However from reading the documentation on Django's default user class it seems like the password should be encrypted. My user class is inheriting from the default user class so I'd think I'd be fine here. This is my User class: class User(AbstractUser): class Meta: db_table = 'auth_user' This is my Form Class: class UserRegisterForm(forms.ModelForm): email = forms.EmailField(label='Email Address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'email', 'email2', 'password' ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError('emails must match') email_queryset = User.objects.filter(email=email) if email_queryset.exists(): raise forms.ValidationError('This email is already being used') return super(UserRegisterForm,self).clean(*args, **kwargs) And this is my Form: <form method="post" action="{% url 'sign-up' %}"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="signup"> <input type="hidden" name="next" value="{{ next }}"> </form> Any ideas … -
Django: How to mangle through relations
I have an instance of ModelA and want to query all instances of ModelC which are related to ModelA through ModelB. ModelA -> all ModelB instances with FK rel_a = ModelA -> rel_c.all() class ModelA(models.Model): # fields pass class ModelB(models.Model): rel_a = models.ForeignKey('ModelA', ...) rel_c = models.ManyToMany('ModelC') # more fields class ModelC(models.Model): # fields pass I know how I would do this in SQL but I really do not get how I should unmangle these relations -
Using beautiful soup in Django
How would I use information captured in a Django model field to retrieve data with beautiful soup and display it in a Django template -
Integrating bootstrap template with django app
I'm working on a django web app and I wanted to integrate this bootstrap template (https://startbootstrap.com/previews/sb-admin/) to my django web app. Is it possible and if yes could you please detail to me the steps to do that. I'm sorry if my question is not detailed I'm still a newbie and I really need to do this. Thanks in advance -
Front-end, back-end or database: where should I alter data to generate my components?
I'm somewhat new to programming. We're creating an application using React, Redux and Django Rest Framework. The main goal of this application is to present educational data in a nice and comprehensible way. I'm using Nivo to create all sorts of charts. Right now we're creating a simple line chart to show the score every school reached in a certain national test here. Nivo needs the data to generate the charts in this JSON format: [ { "id": "japan", "color": "hsl(175, 70%, 50%)", "data": [ { "x": "plane", "y": 52 }, { "x": "helicopter", "y": 110 }, { "x": "boat", "y": 210 }, ] } ] The data I have is something like this: school_id school_type year grade first_application_score second_aplication_score avg 1 public 2015 3 6.5 7.2 6.9 1 public 2016 4 7.9 7.1 7.5 2 private 2015 5 5.5 6.5 6.0 My question here is: where should I alter the data to create the chart's data? In my actual level of understanding web programming, I could use the following strategies: I can create new tables in the database using SQL. This tables will have the x and y values, so the API in Django will do no calculations, just … -
Don't want to use the Django admi template
I want to render my own html page which execute python script and output on my html page instead of using the django web template where I would have to edit the settings.py or add App. All the same I want to be using the django web framework. How should go by it? -
Good way to run ONE indefinite process on Django Framework
I'm building a web app using a Django framework. There isn't much user interaction with only a few static links, navbar, and a few plots which come from my app itself. The main part of the app comes from a python script which reads data from an external source, does some data processing on it, and then writes to my django database. Then after writing to the database a new page is created with information about the database entry. Note that there is no user interaction so no starting or stopping the task. I want the task to run in the background 24/7. Thus far I've looked into celery and django-background-tasks. Celery seems like a bit much for my use case. I don't think I need a broker service as I just want to run 1 task which the user will never interact with. Additionally, I don't need multiple workers. Django-background-tasks seems like a good lightweight alternative but it seems it does not support indefinite tasks without having to refresh the task every once in a while (ideally I don't want this). Is there a tool that is better suited for this use case? Or am I just completely misunderstanding … -
Simple Tree Using Django and CSS
I have a queryset which returns [{'id': 1, 'username_id': 32, 'schoolCode_id': 2, 'classVal_id': 'CL002', 'class_section': 'A'}, {'id': 2, 'username_id': 33, 'schoolCode_id': 2, 'classVal_id': 'CL002', 'class_section': 'A'}, {'id': 3, 'username_id': 34, 'schoolCode_id': 2, 'classVal_id': 'CL002', 'class_section': 'A'}, {'id': 4, 'username_id': 35, 'schoolCode_id': 2, 'classVal_id': 'CL002', 'class_section': 'B'}, {'id': 5, 'username_id': 36, 'schoolCode_id': 2, 'classVal_id': 'CL003', 'class_section': 'C'}, {'id': 6, 'username_id': 37, 'schoolCode_id': 2, 'classVal_id': 'CL003', 'class_section': 'C'}, {'id': 7, 'username_id': 38, 'schoolCode_id': 2, 'classVal_id': 'CL003', 'class_section': 'C'}, {'id': 8, 'username_id': 39, 'schoolCode_id': 2, 'classVal_id': 'CL003', 'class_section': 'D'}, {'id': 9, 'username_id': 40, 'schoolCode_id': 2, 'classVal_id': 'CL008', 'class_section': 'A'}, {'id': 10, 'username_id': 41, 'schoolCode_id': 2, 'classVal_id': 'CL008', 'class_section': 'A'}, {'id': 11, 'username_id': 42, 'schoolCode_id': 2, 'classVal_id': 'CL008', 'class_section': 'A'}] I would like to display a tree structure in my template like <classVal_id 1> <class_section> <Username_id 1> <username_id 2> <class_section B> <Username_id 3> <Username_id 4> <classVal_id 2> ............... I tried using "ul" and "li" using nested for loop. But somehow got stuck and could not print the values. I tried django-treebeard but seemed a little complicated. Is it possible to print the data using the queryset ? I want to use the snip on the url https://bootsnipp.com/snippets/ypNAe to print my data. Any help would … -
How to pass logged user's id to CreateView
I can't figure out how to pass current user's name as the post's author automatically. If add the author fields = ['headline', 'quote', 'author'], the dropdown menu is shown and passed, but I need the logged user's name to be the default. my view: class PostCreate(CreateView): model = Post user = User fields = ['headline', 'quote'] success_url = '/index' template_name = 'base_homepage.html' @login_required() def get_context_data(self, **kwargs): kwargs['latest_posts_list'] = Post.objects.order_by('-id') return super(PostCreate, self).get_context_data(**kwargs) my model: class Post(models.Model): _id = models.ObjectIdField headline = models.TextField(max_length=255) quote = models.TextField(max_length=140) creation_time = models.DateTimeField(editable=False).auto_now_add author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.headline[:25] -
Problem with Django 3.1 include() function when defining urls for learning_logs web app from Python Crash Course
I get a type error when trying to load my website. path('login/', {'template_name': 'users/login.html'}, name='login') File "/Users/jakeziegelbein/Desktop/crashCoursePython/learning_log/11_env/lib/python3.8/site-packages/django/urls/conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). Here is the code from the root urls.py file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('learning_logs.urls')), ] Code from the urls.py file from the users app. """Defines URL patterns for users.""" from django.urls import path, include from django.contrib.auth import login from . import views app_name = 'users' urlpatterns = [ # Login Page.dc path('login/', login, {'template_name': 'users/login.html'}, name='login') ] I don't know why I'm getting the error mentioned above. I looked at the django url documentation and it seems I'm writing my code accordingly. Any ideas on the source of the error? -
Which is the best Front-End language combination with a Django application? [closed]
Can you suggest the best front-end language to be used with a Django project. Is it (Angular, React or Vue.js) or the inbuilt Jinja2 is enough? Does it depends case to case, if yes, for what different scenario's they are most suitable to use? -
Why won't os.environ.get return the new value set in bash profile?
I have a django application and I recently changed a password on an email that uses the google smtp. I've updated the password in the bash profile, but when I run settings.py the os.environ.get returns the previous password in the bash profile. old password: ABC new password: XYZ EMAILS_HOST_PASSWORD = os.environ.get("EMAIL_PASS") print(EMAILS_HOST_PASSWORD) still returns ABC instead of XYZ -
How to Use Django Management Command For One Time Tasks
I want to schedule one time tasks with Django Management Command. I tried following this tutorial but couldn't figure out how to NOT do a recurring task. Let's say I want something to run on January 25th, 5:00 PM UTC 2021 ONCE. How could I do this? Thanks! -
Django3.0: Images from database not showing-up after debug=False
After debug=False in my settings. Images from database not showing up otherwise they were. Static files are showing up real good. Even my media files were showing up before debug=False. Database has correct addresses of files but covers not showing up. Following is the code, how I am accessing cover images. <div class="product-top"> <img src="{{ product.cover.url }}" alt="book-image"> <h5>{{ product.title }}</h5> </div> my settings.py related code: import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) TEMP_DIR = os.path.join(BASE_DIR, 'templates') # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'abc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'abc@gmail.com' EMAIL_HOST_PASSWORD = 'xyz' EMAIL_PORT = 25 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'abc@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' BASE_URL = '127.0.0.1:8000' MANAGERS = ( ('abc', "abc@gmail.com"), ) ADMINS = MANAGERS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'crispy_forms', # myapps 'myapp', ] AUTH_USER_MODEL = 'accounts.User' STRIPE_SECRET_KEY = 'abc' STRIPE_PUB_KEY = 'abc' MIDDLEWARE = [ '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', 'debug_toolbar.middleware.DebugToolbarMiddleware', # Simplified static file serving. 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES … -
How do I retrieve the name of superuser in Django?
users = User.objects.all() post.author = users.name Considering that 'User' is where superuser's info is stored in the database. It throws an error as: 'Query Set' object has no attribute 'name' -
Django + S3 Signature expiration
Should my django-storage instance be storing the S3 signature in the database along with the image name? If so how do you regenerate a new key on each request assuming the old request expiration is already past? models.py def user_directory_path(self, filename): return 'profile/user_{0}/images/profile/{1}'.format(self.user.id, filename) ... ... user_image = models.ImageField(upload_to=user_directory_path, storage=PrivateMediaStorage(), blank=True) storage_backends.py class PrivateMediaStorage(S3Boto3Storage): location = 'private' default_acl = 'private' file_overwrite = False custom_domain = False Sorry new to Django, want to make sure my logic is correct. -
'<frozen importlib._bootstrap>' django error
I have been receiving the error below, whenever I wish to run the server (python manage.py runserver) However as of late, I have been getting the error below. The last thing that I did was carry out tests for my project over a week ago. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_filters' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute … -
could not concatenate string with int inside action method of url inf form tag in python Django
todo_item.id is an int and rest of addres is string so it is not concatinating . Please tell me how to concatenate it. I search a lot but found nothing -
Django-Filters - ListApiView
I am following this documentation on how to implement django-filter: https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html#using-the-filterset-fields-shortcut import django_filters from django_filters import rest_framework as filters class PostApiView(ListAPIView): filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ('category', 'location') def get(self, request, format=None): post_qs = Post.objects.all() po_serializer = PostSerializer(post_qs, many=True) po_data = po_serializer.data data = { 'post_data': [{ 'title': po['title'], 'content': po['content'], 'category': po['category'], 'location': po['location'], 'author': po['author'], 'date_posted': po['date_posted'], 'author_image': po['author_image'], 'post_pk': po['post_pk'], 'author_desc': po['author_desc'], 'contact': po['contact'] } for po in po_data], } <form class="filter_form" action="" method="get"> {{ filter.form.as_p }} <button class="filter_form_btn" type="submit">Suche</button> </form> The form does not render Thank you for any suggestions -
What does the underscore before the label value in Django forms mean
I have came through the UserCreationForm in the django source code here. Here is the question, if you look at both password fields you will see an underscore before the label value, I wonder what's the purpose of it, because it's not written in the documentation since I searched for it. class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _('The two password fields didn’t match.'), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False, help_text=_("Enter the same password as before, for verification."), ) -
Improve performance of processing API created using Django-rest-framework
I want the above API "story": { "pranay": [ 9, 2 ], "eeee": [ 8, 6, 4, 3, 1 ], "pranay56n": [ 5 ] } And I am getting it using the method below. But there is a problem it is okay to have the method if my objects are less but if there are 100000 objects than it will lower the performance. class Follow(models.Model): user = models.OneToOneField(User, verbose_name=_("User"),related_name="user" ,on_delete=models.CASCADE) following = models.ManyToManyField(User, verbose_name=_("Following"),related_name='is_follower',blank=True) class StorySerializer(ModelSerializer): story = SerializerMethodField() class Meta: model = Stories fields = ('story',) def get_story(self,request): user = self.context.get("request").user follower_ids = [x.pk for x in user.user.following.all()] qs = Stories.objects.filter(user__id__in=follower_ids, active=True).order_by('-date_created').values_list('user__username',flat=True) data = {} for obj_user in qs: data[obj_user]=Stories.objects.filter(user__username__exact=obj_user, active=True).order_by('-date_created').values_list('pk',flat=True) return data Is there any way that will increase its performance?