Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To use class FullNameForeignKeyWidget(ForeignKeyWidget) to limit the query returned
I am using django-import-export to import data to my book table. The book model has foreign key to Author table, for which i use Author number which works fine. However, each year there might be same author with the same number. What I am trying to do is to limit the query as Author.objects.filter(year=year). Reading the documentation I found https://github.com/django-import-export/django-import-export/blob/fe491d8af6220e29cf98b84c4d76a0d10e4ce693/import_export/widgets.py#L350 Can someone advise how to aprroach this? -
create db.connection custom class wrapper, keep getting "django.db.utils.InterfaceError: cursor already closed"
im trying to make custom class wrapper for "django.db.connection", but im keep getting "django.db.utils.InterfaceError: cursor already closed". the working code is something like this if without custom class wrapper (copied from ./manage.py shell) : >>> from django.db import (connection as con) >>> with con.cursor() as q: ... q.execute('select * from master.years a where a.years = %s', [str(2019)]) ... f = [f.name for f in q.description] ... for b in q: ... print(dict(zip(f,b))) my wrapper webapp/mine/db.py : class query_00: def __init__(self, db_con, db_sql, db_stmt = []): self.db_con = db_con self.db_sql = db_sql self.fields = [] with db_con.cursor() as self.query: self.query.execute(db_sql, db_stmt) self.fields = [f.name for f in self.query.description] # for entry in self.query: # yield dict(zip(self.fields, entry)) # self.query = db_con.cursor() # must return self, because # AttributeError: 'NoneType' object has no attribute 'result' def __enter__(self): return self # self.query.execute(self.db_sql, self.db_stmt) # self.fields = [f.name for f in self.query.description] # pass def __exit__(self, exc_type, exc_value, traceback): # is this necessary? # self.db_con.close() pass def result(self): for entry in self.query.fetchall(): yield dict(zip(self.fields, entry)) # not working # for entry in self.query: # yield dict(zip(self.fields, entry)) # not working # yield dict(zip(self.fields, entry)) # pass then i try it on ./manage.py shellby typing … -
How to authenticate new users using only social media auth but also only by Admin user invitation?
My web app currently uses django-allauth to authenticate users via sign-up. What I want to achieve is that sign-up is disabled except for the situation where current Admin users send an invitation (via email) to someone asking them to sign-up, and then the sign-up/registration take place using only a third party source (i.e. social media authentication), such as Office 365, Facebook, LinkedIn etc. As part of this authentication pipeline, I would like the Admin user who is inviting to be able to select which social media/third parties the user is allowed to authenticate with. As I have said, I currently use django-allauth to authenticate using Django. I know django-invitations allows users to invite other users to join, but I not sure if it can be restricted to Admin users only or to just third party auth, or let me select third party auths. In my settings.py I have: ACCOUNT_OPEN_SIGNUP = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'optional' ACCOUNT_EMAIL_CONFIRMATION_EMAIL = True ACCOUNT_EMAIL_CONFIRMATION_REQUIRED = True ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_APPROVAL_REQUIRED = True with an invitation template etc. which lets me invite users. -
Why filelist is empty even after uploading images
I am trying to upload multiple images of a model(say ChannelPostImages) to django view.But when i'm using request.FILES.getlist it's empty. <form method="POST" id="uploadimages" action="/Channels/SMusic/ChannelAdminPost/34/"> {% csrf_token %} <input id="imager" type="file" name="Images"accept="image/*" multiple="True"> <button class="submitter">POST</button> </form> while my view function is as follows:- def ChannelAdminPoster(request,channelname,userid): if request.user.is_authenticated: files = request.FILES.getlist('Images') print(files) for f in files: print(f) objec=get_object_or_404(channel,ChName=channelname) else: return redirect('home') It should be printing path of images on command prompt.But it is showing an empty query. -
How can i authenticate users without giving him access to /admin?
I'm using the djangos default auth method with superuser but in my system i need to have another login in another dashboard for my customers, if i use the default login methods my customers will have access to /admin, is possible to set a differente kind of authentication for my customers and redirect them to a differente dashboard? how? -
Django AttributeError: 'ForwardManyToOneDescriptor' object has no attribute <field>
I've got 4 related models in one app: class AssetType(models.Model): id = models.AutoField(primary_key=True) type_name = CaseInsUniqueCharField(name='Type Name') parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, verbose_name='parent') type_field = models.ManyToManyField('AssetField', blank=True) history = HistoricalRecords() # Return Asset Name for Queries def __str__(self): return self.type_name class AssetField(models.Model): id = models.AutoField(primary_key=True) field_name = CaseInsUniqueCharField(name='Field Name') history = HistoricalRecords() # Return Field Name for Queries def __str__(self): return self.field_name class AssetFieldValue(models.Model): id = models.AutoField(primary_key=True) value = models.CharField('value', blank=True, max_length=100) field = models.ForeignKey('AssetField', on_delete=models.CASCADE, blank=False) asset = models.ForeignKey('Asset', on_delete=models.CASCADE, blank=False) history = HistoricalRecords() # Return '<Asset> - <Value>' for Queries def __str__(self): return str(self.asset) + "-" + str(self.field) class Asset(models.Model): id = models.AutoField(primary_key=True) asset_type = models.ForeignKey('AssetType', on_delete=models.CASCADE, verbose_name='Type') asset_name = models.CharField('Name', max_length=100) asset_tag_no = models.CharField('Tag Number', max_length=20, blank=True, null=True) asset_manufacturer = models.ForeignKey('AssetManufacturer', on_delete=models.SET_NULL, null=True, blank=True) asset_storage_location = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) asset_list_price = models.PositiveSmallIntegerField('List Price', blank=True, null=True) asset_needs_pat = models.BooleanField('Needs Electrical Test', null=True) asset_fields = models.ManyToManyField('AssetField', blank=True, editable=False) history = HistoricalRecords() # Return Asset name for queries def __str__(self): return self.asset_name And I have added in a post-save handler just under the Asset Class @receiver(post_save, sender=Asset) def my_handler(sender, **kwargs): t = Asset.asset_type f = t.type_field.all() for i in range(1,f.count()+1): Asset.asset_fields.add(f[i-1:i]) That is supposed to add the AssetFields … -
Django file-cache slow when retrieving item
I am trying to use the Django frameworks file cache for caching two items: A dict (1.7MB) A list (5.4MB) My goal is to fetch these items on startup instead of parsing files with a lot of logic. Anyway, retrieving the dict is quite fast, but retrieving the list is much much longer (more than five times as long). Why is this? And is there anything to do with it, or do I need to look into another type of cache? Thank you. -
How to remove built-in errorlist of Django model forms?
I made a model form in Django that enables user to create an instance of that model. All is well save one thing. Built-in error lists of Django is annoying. I want those errors to show itself when user actually made that error. When I open my page it looks like this Please help me how do I remove these errorlist temporarily so that when user left input fields empty. It pop ups itself? I don't know if you need these codes to solve this problem, but here it is: views.py file here @login_required(login_url='/accounts/login/') def article_create(request): article_form = ArticleForm(request.POST or None, request.FILES) if article_form.is_valid(): instance = article_form.save(commit=False) instance.author = request.user article_form.save() return render(request, 'blog/article-create.html', {'form': article_form}) Thank you -
Django Creating Custom User models
Oh hey am making a website through Django and i wanna create a similar model for the Users model (default user model came with django) I have tried everything i have found from google django docs and i couldn't Can anyone help? Or help me to make a login system for my normal model For ex I have created i normal model called accounts and there is a field in it called loggedin Whenever i login i set it to True means logged in. And if i logged out by the logout button i set it to false now lets take in consideration if i have closed the web browser Immediately i want to set it to False Any help? -
Trying to delete all objects older than 7 days in django and I keep getting TypeError: unorderable types: DeferredAttribute() < datetime.datetime()
I am trying to create a web page that displays a status that is uploaded to a MySQL server from a sonic sensor. I've tried many different arrangements of the selections but none seem to work. When I created my first Django project I followed the tutorial and their example, selecting objects created in the past day seemed to work. return self.pub_date >= timezone.now() - datetime.timedelta(days=1) In my project, I just changed days to 7 and I changed around >= to be <. Then I started getting "TypeError: unorderable types: DeferredAttribute() < datetime.datetime()". My models.py: from django.db import models import datetime from django.utils import timezone class garage_door(models.Model): date = models.DateTimeField(auto_now_add=True) state = models.CharField(max_length=6) def __str__(self): return str(self.date)[:19] def select_old(self): return self.date < timezone.now() - datetime.timedelta(days=7) My views.py where I am calling this function: from django.shortcuts import render from django.http import HttpResponse from dash.models import garage_door def dashboard(request): garage_door.select_old(garage_door).delete() return HttpResponese("Temp Response") I want the program to (as stated above) delete all objects older than 7 days, but for some reason, I get this error. What I got from it is that I am comparing two uncomparable variables, but I don't know how to fix that and I don't even know … -
Frontend code directly access http instead of https and cause mix content error
As an academic project, we host our web application with Amazon S3 (For Angular) and Apache Server (For Django). We have made both sites https (for both frontend and backend). We can access the backend successfully on our localhost using ng serve. However, for the production site, it always gives us a mixed content error (try to connect HTTP for our backend). But we actually put https in our angular code. Are there any suggestions on that? Attached is our frontend code export class AuthenticationService { private ip: string = 'https://sunrise.99jhs.com'; authenticate(username: string, password: string) { const headers = new HttpHeaders(); headers.append('Access-Control-Allow-Origin', '*'); return this.http.post<any>(this.ip + '/api-token-auth/', {username, password}, {headers}); } Attached is error message Mixed Content: The page at 'https://sunrise.4jhs.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://sunrise.99jhs.com/api-token-auth'. This request has been blocked; the content must be served over HTTPS. We build the angular code using ng serve --prod -
How do I fix '... is not a registered namespace' Django 2.1 error
so Im building and simple mooc plataform using Django 2.1 and Im having a problem. Here you can find my entire project but ill describe all situation above, and here u can find a entire printscreen of django error. So i have this project called TamerMooc, this project has 2 apps. A core app and a courses app. This is the /courses/views.py file: from django.shortcuts import render, get_object_or_404 from .models import Course def index(request): courses = Course.objects.all() template_name = 'courses/index.html' context = { 'courses':courses } return render(request, template_name, context) def details(request, slug): course = get_object_or_404(Course, slug=slug) template_name = 'courses/details.html' context = { 'course': course } return render(request, template_name, context) And this is the /courses/urls.py file: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('',views.index ,name='index'), path('<slug:slug>', views.details , name='details'), ] And at least the /core/templates/base.html file quoted in the error file. <!doctype html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Simple MOOC - Uma simples plataforma de ensino a distância" /> <title>Tâmer MOOC</title> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css"> <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> </head> <body> <div class="header"> <div class="pure-menu pure-menu-open pure-menu-fixed pure-menu-horizontal"> <a class="pure-menu-heading" href="{% … -
Delete mutation in Django GraphQL
The docs of Graphene-Django pretty much explains how to create and update an object. But how to delete it? I can imagine the query to look like mutation mut{ deleteUser(id: 1){ user{ username email } error } } but i doubt that the correct approach is to write the backend code from scratch. -
'Not Found: /' Django server error when trying to map views to urls
I am trying to map my project's urls.py to an application's urls.py to create modular views. Project urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('first_app/', include('first_app.urls')), ] app urls.py: from django.conf.urls import url from first_app import views urlpatterns = [ url('', views.index, name='index'), ] error Django version 2.1.7, using settings 'first_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: / [31/Mar/2019 14:28:54] "GET / HTTP/1.1" 404 2038 -
Django don't see static files
So the thing is that django simply can't recognize the static files. No matter what have i tried it just doesn't work. I tried changing the from global searching way to a direct url of the css file, none of this seems to work. The structure of my project looks like this --> Project structure DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATIC_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") from django.contrib import admin from django.urls import path from something.views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', home), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Monkeys</title> <link rel="stylesheet" type="text/css" href="{% static 'css/file.css' %}"/> </head> Could find the answer in any topic on the internet so i'm hoping you could help. -
i have some data stored in mongodb,whose data structure is quite complex,i wonder how to show them in django
i scrapped some data using scrapy,and i stored them in mongodb,and they have pretty nested structures,like dict in dict "_id" : ObjectId("5c9ca5b051045c0240071f0b"), "page_url" : "http://tieba.baidu.com/p/6077050002", "author" : "允你一世苏心", "img_url" : { "http://imgsrc.baidu.com/forum/w%3D580/sign=9ea56ae7a7ec8a13141a57e8c7029157/aa869925bc315c60fd2125e783b1cb13485477fe.jpg" : { "ret" : 0, "msg" : "ok", "data" : { "tag_list" : [ { "tag_name" : "normal", "tag_confidence" : 72, "tag_confidence_f" : 0.723125 }, { "tag_name" : "hot", "tag_confidence" : 27, "tag_confidence_f" : 0.276846 }, { "tag_name" : "porn", "tag_confidence" : 0, "tag_confidence_f" : 2.86029e-05 }, { "tag_name" : "female-breast", "tag_confidence" : 100, "tag_confidence_f" : 1 }, { "tag_name" : "female-genital", "tag_confidence" : 0, "tag_confidence_f" : 0 }, { "tag_name" : "male-genital", "tag_confidence" : 0, "tag_confidence_f" : 0 }, { "tag_name" : "pubes", "tag_confidence" : 0, "tag_confidence_f" : 0 }, { "tag_name" : "anus", "tag_confidence" : 0, "tag_confidence_f" : 0 }, { "tag_name" : "sex", "tag_confidence" : 0, "tag_confidence_f" : 0 }, { "tag_name" : "normal_hot_porn", "tag_confidence" : 8, "tag_confidence_f" : 0.088255 } ] } } }, "title" : "小声问一句重修能翘课吗,真的有事情,会不会点名呀,在线急求!" } and i want to display the data using django,but i'm new to django,i just don't know how to design the models so that they suit my data and display them -
How to cotinuosly append data from DB2 server to sqlite using preferably django and if nothing else then python alone code
I am writing a django website that has some reports that pulls data based on DB2 database. Since I have only read only access to that database, I want the data from DB2 to be continuosly appended (or appended at intervals of lets say 20 minutes) to sqlite database being used by django. Now I am totally new to python as well hence I am blank with what should I use for this. Is there any django method that can be implemented or should I write a python only script to copy the data. Lets say I have a database with fields - DEAL,BUSINESS,CUSTID,REPID,REPNAME in DB2 (I don't have any primary key here since the database if very old). I want to continuisly copy this data from DB2 to Sqlite. What should be the simplest code? Please help. -
ListView is not pass data to template in django
Every instructions are followed correctly but the data is not printed at template tags. views.py from Appadmin1.models import UserProfile,Player,Tournament from django.views.generic import ListView class tlistView(ListView): content_object_name ='tournament_list' model = Tournament template_name = 'admin/tour_list.html' urls.py from admin_dashboard.views import * app_name = 'adminD' urlpatterns = [ # views.adminD path('',adminD,name='admin_D'), path('tour-listview',tlistView.as_view(),name='tour_list'), ] tour_list.html <tbody> {% for details in tournament_list %} <tr class="table100-head"> <td class="column1">{{ details.eventname }}</td> <td class="column1">{{ details.venue }}</td> <td class="column1">{{ details.date }}</td> <td class="column1">{{ details.time }}</td> <td class="column2"><a href="#">Edit</a></td> </tr> {% endfor %} </tbody> -
How to receive html anchor tag value in Django views.py?
I'm trying to send string value from anchor tag in a div in html i.e "news.id" to views.py. I'm not sure if "single_post/{{ news.id }}" is correct or not. news.id could be 5c9f94516fe3c761e420333a (for regex) .html <div class="post-continue-btn"> <a href="single_post/{{ news.id }}" class="font-pt">Continue Reading <i class="fa fa-chevron-right" aria-hidden="true"></i></a> </div> I've passed this one somehow but now stuck at URLs.py, here is my URL code URL.py urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^single_post/$', views.single_post), url(r'^<slug:slug>/$',views.single_post), url(r'^index/single_post/$', views.single_post), url(r'^index/$', views.index), url(r'^contact/$', views.contact), url(r'^about_us/$', views.about_us), path('admin/', admin.site.urls),] views.py def single_post(request): project_name = request.GET.get('id') context = {'doc_data': search_query.doc_data(project_name)} return render_to_response('DeepNews/dummy.html', context) How to code things right in .html anchor tag and then what will be the regex for this type of string "5c9f94516fe3c761e420333a" in URL.py so that I can get the value of "news.id" in views.py -
Implementation of Foreign keys in Django
I wrote this model for my app models.py from django.db import models from accounts.models import FrontendUsers from django.utils import timezone # Create your models here. class Jit(models.Model): value = models.CharField(max_length = 100, blank = False) author = models.ForeignKey(FrontendUsers, on_delete=models.CASCADE) date = models.DateField(default=timezone.now() ) In views I have defined a function which will populate table of Jits with indormation taken from user. views.py def new_post (request): if request.method == 'POST': value = request.POST.get('value') if value != '' and value : author_id = int(request.POST['user_id']) jit = Jit.objects.create(value = value,author=author_id) jit.save() return redirect('feed') else: messages.error(request,'There was some problem writing your jit.') return redirect('feed') Error Cannot assign "15": "Jit.author" must be a "FrontendUsers" instance. In simple words I am trying to add author_id to Jit's table so that both tables can be connected. -
Why doesn't DRF translate dutch?
DRF automatically translates response messages for some languages if the right 'Accept-Language' header is present. It does this as expected for e.g. Spanish ('es') and French ('fr'), but apparently not for Dutch ('nl') even though all the necessary translations are available. DRF provides a way to add new translations. But since the translations are already made, this should not be necessary. Django settings (no LANGUAGES setting): MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' Behaviour with other languages: http http://localhost:8000/api/auth/password/reset/ Accept-Language:es ... Content-Language: es ... { "detail": "Método \"GET\" no permitido." } Behaviour with dutch: http http://localhost:8000/api/auth/password/reset/ Accept-Language:nl ... Content-Language: nl ... { "detail": "Method \"GET\" not allowed." } Expected behaviour with dutch (source): http http://localhost:8000/api/auth/password/reset/ Accept-Language:nl ... Content-Language: nl ... { "detail": "Methode \"GET\" niet toegestaan." } -
No module named py in django 1.4
Trying to execute manage.py runserver 0.0.0.0:8000: [31/Mar/2019 08:19:53] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/root/venv/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return self.application(environ, start_response) File "/root/venv/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 241, in __call__ response = self.get_response(request) File "/root/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 177, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/root/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 222, in handle_uncaught_exception if resolver.urlconf_module is None: File "/root/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 342, in urlconf_module self._urlconf_module = import_module(self.urlconf_name) File "/root/venv/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) ImportError: No module named py OS: Ubuntu 14.04 Python: 2.7 Django: 1.4 Installing it with pip install py didn't help. Also I have no alias in my bashrc as suggested here:"import py" > No module named py What is the reason behind this? -
How can I create a countdown timer in Django same for all visitors?
I am working on an reverse time auction project and I would like to know how to create a countdown timer that will show the same time left for different visitors. Do I have to run the clock server side and update every sec with Ajax calls the template? -
Apache Virtualhost for Django Project always throws error
I want to add a custom virtualhost (a django project) to my apache server. I looked up on other answers but nothing helped me. My apache server always throws an error. Here is my Virtualhost in httpd-vhosts.conf: <VirtualHost *:80> ErrorLog "logs/error.log" CustomLog "logs/custom.log" ServerAdmin myproject@myproject.com DocumentRoot "C:/Users/Myzel394/Documents/PROGRAMMIEREN/things/myproject" <Directory /myproject/wsgi.py> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / myproject/wsgi.py <Directory /lib/media> Require all granted </Directory> Alias /media /lib/media <Directory /lib/static> Require all granted </Directory> Alias /static /lib/static </VirtualHost> -
Django - how to fix an empty search bar that is returning all items
I have a search bar. When i try to search without putting any word, it returns all the items from my models. here's is my views.py for search bar def Search(request): queryset = Book.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(genre__name__icontains=query) ).distinct() context = { 'queryset': queryset } return render(request, 'search_results.html', context) i just want to render in my template that there's no match in his query, instead of returning the list of all items.