Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to make Gsmarena.com with django python but i don't know how to make model
`class Item(models.Model): title = models.CharField(max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField()` i want to make Gsmarena.com with django python but i don't know how to make model of this like how to add multiple ram with same smartphone,android upgradation like every time i review itstrong text how can -
Django assign "score" to each "user"
I am trying to practice my skills with django as a beginner, I built this platform with users and quiz. If logged in, the user can take a quiz. My goal here is to print on the "user profile" page the scores of the tests he/she has taken. Do you have any suggestions on how I can link the score to the user? Or do you have any resource to follow? account/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class FormRegistrazione(UserCreationForm): email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] account/urls.py from django.urls import path from .views import registrazioneView urlpatterns = [ path('registrazione/', registrazioneView, name='registration_view') ] account/views.py from django.shortcuts import render, HttpResponseRedirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from accounts.forms import FormRegistrazione # Create your views here. def registrazioneView(request): if request.method == "POST": form = FormRegistrazione(request.POST) if form.is_valid(): username = form.cleaned_data["username"] email = form.cleaned_data["email"] password = form.cleaned_data["password1"] User.objects.create_user(username=username, password=password, email=email) user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect("/") else: form = FormRegistrazione() context = {"form": form} return render(request, 'accounts/registrazione.html', context) core/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.homepage, name='homepage'), … -
Django FileField() upload only Excel Files
this is my model.py class Data(models.Model): """ Model of Data""" user = models.ForeignKey(User, on_delete=models.CASCADE) document = models.FileField(upload_to="documents/%Y/%m/%d") uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.document) forms.py from django.forms import ModelForm from .models import Data class DataForm(ModelForm): class Meta: model = Data fields = ['document'] Kindly asking, I just want to upload Excel file only, What should I do? -
Navigation bar issue in Django
enter image description here I really do not know why my home page look likt this. I can not change the size of the navigation bar so part of my header text is invisible. I tried to manipulate the code but still issue occurs. Header still miss a author box in the header. How and where I can change it? Any help is needed. -
Django elasticsearch dsl not identifying the index i have created
"the '{}' indexes? [n/Y]: ".format(", ".join(index_names))) Document: @registry.register_document class AboutUsDocument(Document): class Index: # Name of the Elasticsearch index name = 'aboutus' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = AboutUs # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = ['our_story','second_section', 'third_section', 'fourth_section', 'five_section','published', ] -
Django Model, Multi value / Admin Area
I have start fresh with Django. I am creating a blog and I need a hint now. I want to add tags to my posts. So I created a model for my tags: class Tag(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name This is my Post Model class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title What is the best way, that the user can select in the admin area tags for the post and more than one or create a new tag? -
Django. How to show some content on only single page without duplicating?
For starters, i'm new in Django. I have a searchbar and i want to show it on only single page. I use {%block searchbar %} {%endblock%} on all pages where I don't want to see the search bar. But suddenly I thought: I'm duplicating the code, and this violates the principle of "DRY". So, how can I display some content on a single page without duplicating this {%block searchbar %} {%endblock%} stuff? In advance, thanks for your help! -
Unknown command in django core managment
I use Docker, Python and Django in my TDD project. When I run dcoker command on console: docker-compose run app sh -c "python manage.py test" The get error with message: Starting recipe-app-api_db_1 ... done Creating test database for alias 'default'... System check identified no issues (0 silenced). ...EE.... ====================================================================== ERROR: test_wait_for_db (core.tests.test_commands.CommandsTestCase) Test waiting for db ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 103, in call_command app_name = get_commands()[command_name] KeyError: 'wait_for_db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/mock.py", line 1348, in patched return func(*newargs, **newkeywargs) File "/app/core/tests/test_commands.py", line 24, in test_wait_for_db call_command('wait_for_db') File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 105, in call_command raise CommandError("Unknown command: %r" % command_name) django.core.management.base.CommandError: Unknown command: 'wait_for_db' ====================================================================== ERROR: test_wait_for_db_ready (core.tests.test_commands.CommandsTestCase) Test waiting for db when db is available ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 103, in call_command app_name = get_commands()[command_name] KeyError: 'wait_for_db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/core/tests/test_commands.py", line 15, in test_wait_for_db_ready call_command('wait_for_db') File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 105, in call_command raise CommandError("Unknown command: %r" % command_name) django.core.management.base.CommandError: Unknown command: 'wait_for_db' ---------------------------------------------------------------------- Ran 9 tests in 5.529s FAILED (errors=2) Destroying test database for alias 'default'... Source … -
How to solve is_hidden error of choicefield in Django model forms?
I am wokring on a form to save data where from and to days are choice fields in models.py. So I make my form Model in forms.py be choice fields. I've done this far. models.py class Create_Class(models.Model): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, default=1) class_name = models.CharField(max_length=150, null=True) from_choice = ( ('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday'), ) from_days = models.CharField(max_length=10, choices=from_choice) to_days = models.CharField(max_length=10, choices=from_choice) from_time = models.TimeField() to_time = models.TimeField() created_on = models.DateTimeField(auto_now=True) forms.py class Create_Class_Model_Form(forms.ModelForm): class Meta: model = Create_Class exclude = ['created_by', 'created_on'] fields = ['class_name', 'from_days', 'to_days', 'from_time', 'to_time'] from_choice = ( ('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday'), ) widgets = { 'class_name': forms.TextInput(attrs={'class': 'form-control'}), 'from_days': forms.ChoiceField(choices=from_choice, widget=forms.ChoiceWidget), 'to_days': forms.ChoiceField(choices=from_choice, widget=forms.Select()), 'from_time': forms.TimeInput(attrs={'class': 'form-control'}), 'to_time': forms.TimeInput(attrs={'class': 'form-control'}), } Views.py def Class_create(request): form = Create_Class_Model_Form(request.POST or None) if form.is_valid(): obj = form.save(commit=False) obj.created_by = request.user.username obj.save() print('successful') messages.success(request, 'Saved Successfully') c_names = Name_of_classes.objects.values('name') templatename = 'genius/class_create.html' context = {'form': form, 'c_names': c_names} return render(request, templatename, context) Error ChoiceField' object has no attribute 'is_hidden' The error is from forms.py Your help to solve this error would be appreciated. -
Django change Migration table name in DB
How can I costume the django_migrations table name? Even I edit the venv.lib.site-packages.django.db.migrations.recorder > MigrationRecorder > meta = db_table = "ABC_django_migrations" the makemigrations cannot detect the changes. I am using Django version: 3.0.5 -
Background task runner for jobs queued in SQLite3
I have a Django web server that has an interface for users to queue jobs into a database called jobs. I'm hoping to make something that'll look at the jobs in the database in run them and delete them when they are done. Is there something that can work with SQLite3 like this and keep checking this database to see if new jobs have been added? -
Creating an annual income field in django models with currency option of all types available in djmoney
I have created annual_income field in django-model like this : annual_income = MoneyField( max_digits=10, decimal_places=2, null=True, default_currency="INR" ) here the default currency has been set to INR. I would like to have the field in such a way that it takes the currency as input, instead of setting it to default 'INR'. In the admin page, this field should be displayed such that there is dropdown option for the currencies -
How can I add a css class to elements conditionally in django?
I have created a template of sidebar in django which is extended by various pages. <ul class="navbar-nav flex-column mt-5"> <li class="nav-item"> <a class="nav-link p-3 mb-2 text-white" href=#> <i class="fas fa-home text-white ml-2 fa-lg mr-3"></i> Dashboard </a> </li> </ul> <ul class="navbar-nav flex-column"> <li class="nav-item"> <a class="nav-link p-3 mb-2 text-white" href="{% url 'a' %}"> <i class="fas fa-briefcase text-white ml-2 fa-lg mr-3"></i> Business </a> </li> </ul> <ul class="navbar-nav flex-column"> <li class="nav-item"> <a class="nav-link p-3 mb-2 text-white" href="#"> <i class="fas fa-chart-pie text-white ml-2 fa-lg mr-3"></i> Analytics </a> </li> </ul> The links shown above direct to various pages and are present in sidebar i.e the template. I have created two css classes current and sidebar-link to show which link from the above is active and which are sidebar links. How do I conditionally apply one of these classes to these links depending upon which one is currently active? -
"module not found" when running Celery with supervisor
I'm trying to run celery with django using supervisor. supervisor_celery.conf [program:supervisor-celery] command=/home/user/project/virtualenvironment/bin/celery worker -A project --loglevel=INFO directory=/home/user/project/project user=nobody numprocs=1 stdout_logfile=/home/user/project/logs/celery.log stderr_logfile=/home/user/project/logs/celery.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 stopasgroup=true priority=1000 on runing supervisor , i got following error in logs file:- Unable to load celery application. The module project was not found. project structure is project |-project |-settings |-production.py |-__init__.py |-celery.py |-urls.py |-wsgi.py |-app The contents of __init__.py is:- from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) The content of celery.py is from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.production') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() It would be helpful if anyone can tell me why it's not working? -
Handle simple requests asynchronously using Django REST or with another method?
Firstly, sorry if the question is so obviously (I'm quite newbie). I have a Django project where the user can add or remove, for example, interests to his/her profile (ManyToMany relationship). I've achieve this with 3 views. The first one where the profile's interests are rendered, the second one to add (nothing is rendered, when the user click a link, the view just update the profile and return the first view, the one with the profile's interests) and the third one to remove interest. urls.py path('home/overview/add/<int:interest_pk>', add_view, name="add_view"), views.py def add_view(request,interest_pk): #the third (the one to remove) view is similar user = request.user user.profile.interests.add(Category.objects.filter(pk= category_pk).get()) return redirect('overview') #Overview is the view where the interests are rendered This works but now I'd like to improve this making it asynchronously. So here is my question, should I use Django Rest Framework to handle this kind of request (the ones related to the POST and DELETE methods) or is there any other method? Note: I'm not using forms to send the information (I'd rather not to use it because it's simpler to send in an url the pk of the interest and handle it in a view) and I think it could be … -
Django allauth messages piling on on login screen
I'm using Django Allauth and after a user goes through the steps, confirms and signs in, if they log out and go to the login screen, they see a bunch of old messages. The design of my site doesn't have messages displayed on every screen, so they're piling up and showing all at once. How do I clear these before the user sees the whole pile? -
Adding StreamField call-to-actions to base.html using Wagtail CMS
Hi I'm new to using Wagtail and I'm working on a client website. What I aim to do is to dynamically link my wagtail pages to our sidebar, which is currently in our base.html in the main app folder's templates directory, the one with settings.py. I was wondering if there's a way to render a call to action for the base.html here. Or if I should make a separate app instead and create a base.html there, which extends to all the other templates I'll use for the rest of the website. Thank you! -
Django deployment in Hostgator VPS
I'm trying to run django using mod_wsgi module in easyapache4 on CentOS 7 VPS provided by Hostgator. I'm new to this. I've no experience in deploying Django apps on live servers but I've deployed in our office local network in an Ubuntu server machine. I've this responsibility to deploy Django apps on Hostgator VPS which we already had for sometime for deploying PHP based Wordpress, Magento websites and am not looking to invest some money for any other provider since we already have a VPS. Our Hostgator Reseller VPS account has CentOS 7, easyapache 4 and I've installed mod_wsgi successfully which was not pre-installed. Case 1: PHP and Django on same domain We usually run our client projects in our domain like www.ourdomain.com/php/php_project_one/. To run django on the same domain in a differrent path to day like www.ourdomain.com/python/python_project_one/ how should the virtual host configuration be ? I know that whenever i register a new server space account through WHM a virtual host configuration is added to apache config file for that particular domain. So, should i be editing that virtual host configuration to create this said Case 1 ? What I tried is, adding additional configuration at the end of … -
Javascript to detect "waiting for locahost" when the form is submitted
When i submit a form below, it shows "waiting for localhost" till the response is received from the django view. How do i detect that event for ("waiting for locahost ") in javascript. (Note: I dont want to send a AJAX request, just a form submit with "POST" method) Please help. <form class="navbar-form" role="search" action ="{%url 'search:search'%}" method="POST"> {% csrf_token %} <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q" id="v_id" autocomplete="off"> <div class="input-group-btn"> <button class="btn btn-success" type="submit"><i class="glyphicon glyphicon-search"></i></button> </div> </div> </form> -
Is knox token is safe are not?
I'm using Drf(django rest framework) for my back end development. I tried to use Knox-token for authentication and token generation. I new to this knox-token. I need to know is Knox token is safe are not?. I'm going to develop web based product. So the product must be safe with full secure. Can i use knox-token for my product? -
How to disable Enforce HTTPS for localhost auth testing?
I tried to configure social authentication via Facebook in my Django project. As I am testing at localhost (already included the http-based site in ALLOWED_HOSTS) , I need to disable Enforce HTTPS. My fb app is now in development mode, but by default Enforce HTTPS is enabled and couldn't be changed apparently. How can I fix it? Thanks! -
Using Browser Router in react-router-dom with Django backend
I'm building an application that uses React as front-end and Django Rest as back-end. From front-end, I'm using react-router-dom for declarative routing and Django only serves API So when user enters an URL like this https://myapp.com/something/something-else, it's actually handle by Django and it will return an error since Django doesn't know which page to lead to with this URL. It should be handled by React instead. One of the workaround I have is to use a Hash Router, so the URL will look like this (with the hash symbol): https://myapp.com/#/something/something-else But there have been cases where user will just key the URL without the hash sign (as they didn't know). Is there away to handle this without using Hash Router? -
File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax
I will develop the web using Django, but when I try to runserver, it gives: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax This is the code for manage.py - #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'firstsite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() I am using django 3.0.5 and python python 3.8.2 how to solve ? -
Mudar o estilo de um formulário do Django
Olá, estou fazendo uma página de edição da conta do usuário, porém quando fui fazer o formulário usando o django não consegui mudar o style dela. Como posso fazer o formulário do django ficar dessa forma? Tentei fazendo da forma tradicional porém nada. https://i.imgur.com/P09UMkT.png views.py @login_required def edit(request): form = EditAccountForm() context = {} context["form"] = form return render(request, "accounts/edit.html", context) form.py class EditAccountForm(forms.ModelForm): def clean_email(self): email = self.cleaned_data["email"] if User.objects.filter(email=email).exclude(pk=self.instance.pk).exists(): raise forms.ValidationError("Conta já existente com esse email!") return email class Meta: model = User fields = ["username", "email"] edit.html <body data-spy="scroll" data-target=".navbar" data-offset="50"> <div class="container py-2 mt-5"> <div class="row my-2"> <div class="col-lg-4"> <h2 class="text-center font-weight-light">User Profile</h2> </div> <div class="col-lg-8"> </div> <div class="col-lg-8 order-lg-1 personal-info"> <form role="form" method="post"> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">Nickname</label> <div class="col-lg-9"> <input class="form-control" type="text" value="Teste" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">Email</label> <div class="col-lg-9"> <input class="form-control" type="email" value="teste@gmail.com" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">Password</label> <div class="col-lg-9"> <input class="form-control" type="password" value="11111122333" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">Confirm password</label> <div class="col-lg-9"> <input class="form-control" type="password" value="11111122333" /> </div> </div> <div class="form-group row"> <div class="col-lg-9 ml-auto text-right"> <a href="/"><input type="reset" class="btn btn-outline-secondary" value="Cancel" /></a> <a href="{% url … -
Django login 'NoneType' object has no attribute 'append'
Having an issue with Django Allauth. When I log out of one user, and log back in with another, I get this issue, both locally and in production. I'm using the latest version of Allauth, Django 3.0.5, and Python 3.7.4. It seems like this is an Allauth issue, but I haven't seen it reported online anywhere else. So just wondering what I can do next to troubleshoot. Login works fine, less I just logged out of another user. 'NoneType' object has no attribute 'append' Request Method: POST Request URL: http://127.0.0.1:8000/account/login/ Django Version: 3.0.5 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'append' Exception Location: /Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/allauth/account/adapter.py in authentication_failed, line 507 Python Executable: /Users/[USERDIR]/Sites/frontline/venv/bin/python Python Version: 3.7.4 Python Path: ['/Users/[USERDIR]/Sites/frontline', '/Users/[USERDIR]/Sites/frontline/venv/lib/python37.zip', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/odf', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/odf', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/odf', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/odf', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/odf', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/odf', '/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/odf'] Server time: Thu, 16 Apr 2020 17:53:52 -0700 Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/login/ Django Version: 3.0.5 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.postgres', 'common', 'bootstrap4', 's3direct', 'bootstrap_datepicker_plus', 'import_export', 'tinymce', 'allauth', 'allauth.account', 'allauth.socialaccount', 'debug_toolbar', 'dashboard', 'marketing'] Installed Middleware: ('debug_toolbar.middleware.DebugToolbarMiddleware', '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', 'django.middleware.security.SecurityMiddleware') Traceback (most recent call last): File "/Users/[USERDIR]/Sites/frontline/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = …