Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dictionary Errors with Django Intermediate Model
I have three tables. Table A, B, and C. I have a form where the user can select choices from each table. I need to save the relationship between Tables A & C and the relationship between Tables B & C. The relationships between Tables B&C are saving fine(AssignmentManager). However, the relationships between Tables A & C are not. They are linked through an intermediary model. I'm trying to follow the documentation examples, but I don't know if I'm interpreting them right. https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany I keep getting one error after another. The latest one is a multi key dictionary error. The intermediary manager for Tables A and C is the FunctionAssignmentManager. Models.py class AssignmentManager(models.Manager): def relationship (self, Role_id, Assignment_title): select = Assignment.objects.get (id= Assignement_title) roles = Role.objects.get(id=Role_id) select.role.add(roles) select.save class FunctionAssignmentManager(models.Manager): def functionA (self,postData): newrel = FunctionAssignment.objects.create( function = ['function'], assignment = ['assignment'] ) newrel.save() class Function(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to="images") objects = FunctionManager() class Role(models.Model): level = models.CharField(max_length=255) function = models.ForeignKey(Function, related_name="roles") objects = RoleManager() class Assignment(models.Model): function = models.ManyToManyField(Function, through='assignments') role = models.ManyToManyField(Role, related_name='assignments') title = models.CharField(max_length=255) definition = models.TextField() objects = AssignmentManager() class FunctionAssignment(models.Model): function = models.ForeignKey(Function, on_delete=models.CASCADE) assignment = models.ForeignKey(Role, on_delete=models.CASCADE) review= models.TextField() objects = … -
Generic detail view ProfileView must be called with either an object pk or a slug
I'm new to Django 2.0 and i'm getting this error when visiting my profile page view. It's working with urls like path('users/<int:id>') but i wanted to urls be like path('<username>'). Not sure what exactly is the problem. I hope you can help. #views.py class ProfileView(views.LoginRequiredMixin, generic.DetailView): model = models.User template_name = 'accounts/profile.html' #urls.py urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('signup', SignUpView.as_view(), name='signup'), path('login', LoginView.as_view(), name='login'), path('logout', logout_view, name='logout'), path('<username>', ProfileView.as_view(), name='profile') ] #base.html <ul class="dropdown-menu"> <li><a href="{% url 'accounts:profile' user.username %}">View Profile</a></li> <li><a href="#">Edit Profile</a></li> </ul> -
porting an app built using Tornado framework to Django framework
I have an app that was developed using Tornado framework and Angularjs. the app is basically a game with two type of users a moderator and players. the moderator and players exchange data in "real time" and a graph is updated based on their input. I am a decent coder but new to web development and this is just an in case question. Since the app has some issues, and since I will have to learn a framework anyway, I would rather learn Django. I was wondering if there is a resource out there that makes the conversion easier? What I am looking for is advice on how to tackle this in a way where I don't have to go through the documentation of both frameworks before I can do anything useful. Ideally, I'd like to incrementally learn more about both frameworks as I make meaningful edits to the app. -
Django ignores test database settings
I have an app deployed on pythonanywhere which runs fine. Problem is that when I want to run test django, my test database settings is completely ignored. Each time I run test I get the following message.though. Creating test database for alias 'default'... Got an error creating the test database: (1044, "Access denied for user 'funnshopp'@'%' to database 'test_funnshopp$funn'") Database name for the app is funnshopp$funn. It can be seen that django somehow always tries to create the test database by appending test_ to the database name. Never minding what I have in DATABASES settings Below is my full settings file ( Test runs fine on my PC and I am using Django 2.0, though I started the project with Django 1.11) """ Django settings for funnshopp project. Generated by 'django-admin startproject' using Django 1.11.7. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os from django.urls import reverse_lazy from django.core.exceptions import ImproperlyConfigured # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def get_env_variable(var_name): """Get the environment variable or return exception""" try: return os.environ[var_name] except KeyError: error_msg = "Set the {} environment variable".format(var_name) raise … -
I don`t know what means None in django user
class MemberStaffManager(BaseUserManager): def create_user(self, staff_id, company, position, name, password=None): user = self.model( staff_id=staff_id, company=company, name=name, position=position, ) user.set_password(password) user.save(using=self._db) return user Now I'm studying Django custom user but I don't know what means password=None maybe not mean password = null because user.set_password(password) is send password-value please help me. -
ModuleNotFoundError at /polls/register/
I am creating a registration form in django. My project name is FirstProj containing mysite and mysite containing polls. My forms.py is this from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email= forms.EmailField(required = True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user My views.py is this from mysite.polls.forms import RegistrationForm from django.shortcuts import render,redirect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/polls') else: form = RegistrationForm() args = {'form': form} return render(request, 'polls/reg_form.html', args) However my cleaned_data() can't be read and i am getting the following erro. No module named 'mysite.polls' -
How to insert multiple Django blocks into one template?
I am trying to use more different views in one template via different blocks or include method but I have got stuck. My aim is to implement my different views into one template. I tried to more solution but these haven't worked for me. I show these solution: My views: def dashboard_data(request): # Here I collect data from my PostgreSQL database I push these into #Objects and I send it to my test_a.html via render like below. return render(request, 'my_project/test_a.html', send_data) def chart_data(request): #In these view my final goal is to collect data from database and create #charts but for the simplicity I just use a list (a=[1,2,3,4]) and I #push it to the test_b.html and I render it. render(request, 'my_project/test_b.html', send_data)) My templates: 1, base.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>My project</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Include CSS files --> {% load static %} <!-- Include CSS files --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-table.css' %}"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}"> </head> <body> {% block sidebar %} {% endblock %} {% block content%} … -
Django create form wizard from model form
My requirement is to create a form wizard using model form. For example, I have a number of dynamic models, one model has 10 fields and another model have 15 fields. the model form should be split into multiple forms automatically based on fields it contains. I have tried using django-form-tools, but in django-form-tools we need to predefine the form classes in form_list attribute. Is there any other alternative to achieve this without manually doing this -
django project multiple user use the same project
I am new to django and web programming. Right now, I have created a django project for configuration form generation. It allows the user to input the values and generate a configuration form once the user got the URL. Project name: portal, App name: home, input_data.txt: a text file stored the values for the corresponding parameter and it will be read for further processing It works fine for myself, but multiple users use it at the same time. It doesn't work. what can I do in order to allow multiple users use it at the sam time? -
Django webpack loader - KeyError 'DEFAULT' while rendering template
I am trying to get django-webpack-loader to run with webpack but I get an error when I try to render the {% render_bundle 'main' %} tag in my view. I have checked and webpack is successfully generating bundles into my bundles folder, but django-webpack-loader can't seem to render it into the template. I am using default settings for webpack-loader. Does anyone understand this error message and what is causing it? Template error: In template /djangoreact/djangoproject/djangoapp/templates/djangoapp/base.html, error at line 11 DEFAULT 1 : {% load render_bundle from webpack_loader %} 2 : <!DOCTYPE html> 3 : <html> 4 : <head> 5 : <meta charset="UTF-8"> 6 : <title>Example</title> 7 : </head> 8 : <body> 9 : <h1>Django-webpack</h1> 10 : <div id="react"></div> 11 : {% render_bundle 'main' %} 12 : </body> 13 : </html> Traceback: File "/djangoreact/djangoproject/djangoapp/views.py" in index 7. return render(request, template_name ) File "/.virtualenvs/djangoreact/lib/python3.6/site-packages/webpack_loader/config.py" in load_config 33. return user_config[name] Webpack configuration in Django. WEBPACK_LOADER = { 'DEAULT':{ 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } -
Chart JS - Data graph is out of chart
I m new to chart.js, and yet so far i was unable to find answer for this issue. When i add option to chart scaleBeginAtZero: true, some of the top values is out of Y axis boundaries, and in some cases it shows nice view. Maybe it is something to do with the steps of Y axis ? Note in example how Y axis max value 2560 and data in the graph is 2700. Example -
Communication between two django applications
I have one django application that has a model Patient which has all the information about the patient and it's blood sample . I wish to have another application that have some fields of the Patient model and i want both the applications to communicate using some sort of web services so the changes made in the first application are reflected in the second . I'm a novice in django , please share any resources anyone has . If my question is not clear enough, please let me know with a comment. Thank you -
Live Stream a rtsp stream on webpage using ffmpeg
I have a continuous live rtsp stream from my ip cam("rtsp://user:pass@IP_ADDR/PORT"). How can i play this stream on a web page using ffmpeg and websockets(python). -
A function in django view returns a list of dictionary. How can I get value to particular key in its robot test case
Django view function returns: [{u'Name': u'Test Name', u'Description': u'Test', u'Marks': u'10'}] I am Calling the API using RequestsLibrary in Robot and my response seems like a dictionary response but I am unable to fetch value for any particular key. -
Python Heroku App Deployment - not compatible with buildpack
I am trying to deploy a simple "Hello World" Python app in Heroku, but it told me that the deployment is not compatible with buildpack. I've tried to search for the solution in previous similar situation, and did all stuff (e.g. including runtime.txt, requirements.txt etc.) that others can finally solve their problems, but I still have this error message. Would you pls assist to tell why that happens and how I can get it solved? Many thx! What I did:- Created hello_4.py In cmd, go to the respective folder, and run “python hello_4.py” and use browser to go to http://localhost:5000/ Hello world message successfully appears Ctrl+C to stop the localhost $git init saw the .git folder created $git add . $git commit -m "initial commit 4" $pip freeze > requirements.txt Created Procfile in 1 line: web: gunicorn hello_4:app Created runtime.txt in 1 line: python_version = "3.6.3" $heroku create mthd010 --buildpack heroku/python Successful without error message. Refreshed dashboard in Heroku website, and saw that mthd010 app was created $git push heroku master [error message appears] My error message: Image 1 requirements.txt: Image 2 runtime.txt: python_version = "3.6.3" Procfile: web: gunicorn hello_4:app hello_4.py: from flask import Flask app = Flask(__name__) @app.route('/') def … -
.gitignore not ignoring files on current server
I'm trying to import my Bitbucket repo into my Digital Ocean Django server (next to env, static and manage.py. But when I do git add . inside the server directory, and then git status, it still shows the env files there. Any reason why this is happening? Edit: .gitignore env/ /env /bin /lib /media /static /include /reports .DS_Store *.pyc celerybeat-schedule.db __pycache__/ db.sqlite3 settings.py -
Find model instance from table name Django
I've the following table. class TempTable(models.Model): name = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) ... ... class Meta: db_table = 'temp_table' Now suppose I know the table name temp_table. Currently I'm using the following script to get the model instance from table name. from django.db.models import get_app, get_models all_models = get_models() for item in all_models: if item._meta.db_table == 'temp_table': return item Are there any better ways of achieving this..?? -
i want to use year increment after 3 loop in django
in My tag.py @register.assignment_tag def year(): return "2017" In my index.html {% year as years %} {% for Manvi_User in ordering %} <li>{{ Manvi_User.first_name }}</li> {{years}} {{ Manvi_User.dob}} {% if forloop.counter|divisibleby:3 %} {{ years = years+1}} {% endif %} {% endfor %} I want to display starting first 3 name with year 2017 then 3 name with year 2018 and next 3 name should be with year 2019 -
Specifying a namespace in include() without providing an app_name
models.py from django.conf.urls import include, url app_name = "Review" urlpatterns = [ url(r'^books/', include("Review.urls", namespace='reviews')), ] I am providing app_name before my urlpatterns. But it's giving me error while running my code. The errors are given below: File "E:\workspace\python\web\Book_Review_App\Book\urls.py", line 13, in <module> url(r'^books/', include("Review.urls", namespace='reviews')), File "E:\workspace\python\web\Book_Review_App\venv\lib\site-packages\django\urls\conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Please help. -
Display a list of organizations that links to a list of documents belonging to that organization in Django 2.0?
I want my 'index' view to display a list of Organizations. Each organization name should be linked to a Documents view that lists all the Documents uploaded by that Organization. Here's what I have, but I'm lost at this point. urls.py from django.urls import path from website import views urlpatterns = [ path('', views.Index.as_view(), name='index'), path('documents/', views.Documents.as_view(), name='documents'), ] views.py from django.views.generic import ListView from website.models import Organization, Document from django.utils import timezone class Index(ListView): model = Organization template_name = 'website/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context class Documents(ListView): model = Document context_object_name = 'document_list' queryset = Document.objects.all() template_name = 'website/documents.html' index.html - Specifically, how do I create the href's to link to send the organization name to the view? {% extends 'website/base.html' %}{% load static %} {% block title %}Organizations{% endblock %} {% block content %} <h3>Organizations</h3> <hr> {% for organization in object_list %} <a href="{% url 'documents' %}slug={{ organization.name }}">{{ organization.name }}">{{ organization.name }}</a> {% empty %} <p>No Organizations Yet</p> {% endfor %} {% endblock %} documents.html - This is where I want a list of documents, specific to the organization clicked to populate {% extends 'website/base.html' %}{% load static %} {% block … -
Link between Models in Django
I am new to Django. I wanted to know how to link data of the foreign key. Here is the code. class CreateSchool(models.Model): schoolName = models.CharField(primary_key=True, max_length=250) class SchoolDetails(models.Model): createSchool = models.OneToOneField(CreateSchool,to_field='schoolName') principalName = models.CharField(max_length=250) schoolAddress = models.CharField(max_length=500) class kidDetails(models.Model): schoolUID = models.ForeignKey(SchoolDetails,to_field='schoolUID') childName= models.CharField(max_length=245) childUID = models.CharField(max_length=245) my question is when i enter the details of the kid, how to store the kids data with respect to schoolDetails and createschool model from the UI. For example, I need to store kid A in 1 school and i want to store kid 2 in 2 school. How to achieve this. I am completely beginner. Any help would be great. -
Django Python - TemplateDoesNotExist at /blog/
I'm using Django version 1.11.7 and I get the error saying TemplateDoesNotExist. I've been getting this error message when I try to load http://127.0.0.1:8000/blog/. Here is my settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 't$6p8^=z+%8_zm+qb%s8&!!sh@j%)lg4byd@nc8(s5#ozoz&-l' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'taggit', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N … -
Django .annotate with When
I am trying to do a query and get a sum of values based on a conditions. I need all the 'shares" when the 'action' == '+' I have to group by the issues. qs = Trades.objects.all ().filter ( id = id ) .annotate ( d_shrs = Sum ( When ( action = '+', then = 'shares' ) ) ).order_by ( 'issue' ) where am I going wrong? Thanks. -
django views.py avoid duplicate code in views
hello I have crate a simple blog using DJANGO with three class in views.py views.py def blog(request): posts=blog.objects.filter(createddate__lte=timezone.now()).order_by('-createddate') if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'base.html'{'posts':posts}) def blog_details(request,slug): posts=blog..objects.filter(createddate__lte=timezone.now()).order_by('-createddate') pos=get_object_or_404(app_descripts, slug_title=slug) if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'blog_details.html'{'posts':posts,'pos':pos}) def about(request): posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'about.html'{'posts':posts}) in the html I use this way because I have some code: {% extends 'blog/base.html' %} {% block content %} ....................... {% endblock %} In the base.html out of block content I have a simple contaim where I have code for all post ( posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') ). but to view the tthat posts in all pages(blog,blog_details,about) must write this code ( posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate')) in all views to work fine. that happen and for my html contact form because is out of content. how can avoid to execute some code in all views ? -
Django Queryset One to Many list output
I am trying to make the following magic happen: I'm grabbing a HUGE queryset via values, making it into a list, then consuming it by a page. BUT, I want to consume the manys in the one to many relationship (via a parent model) they have with another model, and have them as a list in the list. Is this even a thing? So say I have: # models.py class Game(Odd): type = models.ForeignKey(Type, on_delete=models.PROTECT, null=True, default=1) book = models.ForeignKey(Bookmaker, on_delete=models.PROTECT, null=True, default=23) amount = models.DecimalField(max_digits=10, decimal_places=2, null=True) class TipFromHuman(TimestampModel): tipper = models.ForeignKey(Human, on_delete=models.CASCADE, null=True) odds = models.ForeignKey(Odd, on_delete=models.CASCADE, null=True) tip_against = models.NullBooleanField(default=False) and in a script I'm running: # snippet qs = Game.objects.all().values('id', 'type__name', 'book__name', 'TipFromHuman__tipper__name').distinct() qsList = list(qs) return qs And in the template I can do: {% for q in qsList %} Type {{ q.type__name }} with {{ q.book__name }} from {{ q.TipFromHuman__tipper__name }} {% endfor %} and have it output as: Type Alpha with Green Eggs and Ham from Dr. Seuss, Potatoes, and Green Eggs where there are three associated TipFromHuman records with the tipper names "Dr. Seuss", "Potatoes", and "Green Eggs" Currently, instead of teh desired behavior, I get three different entries in the list …