Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot determine queryset for chaining one-to-many with one-to-one relationship
I have a system where there is a many to one relationship with a number a model (say 1 a -> many b) and that many model has a one to one relationship with another model (say 1 b -> 1 c). Drawn like so: /--- b1 --- c1 / a ---- b2 --- c2 \ \--- b3 --- c3 I'm determined to create a method in that collects all the c's that correspond to a. Given an model system with the same structure to mine, the best I could come up with is shown in the method: Person.find_important_treats(). Is there a better way that does not involve so many calls to the database? from django.db import models class Person(models.Model): """ The 'a' from my above example """ def find_important_treats(self): return (pet.treat for pet in self.pets) class Pet(models.Model): """ The 'b' from my above example """ owner = models.ForeignKey( to=Person, related_name='pets' ) favourite_treat = models.ForeignKey( to=Treat, ) class Treat(models.Model): """ The 'c' from my above example """ pass -
How do i get my context passed through my function-based view on allauth logout page?
I'm trying to send notifications in my navbar to my 'logout.html' page.. but i can't figure out why they're not getting passed.. views.py def account_logout(request): template = 'logout.html' context = hasNotifications(request,template) return render(request,template,context) urls.py url(r'accounts/', include('allauth.urls')), I followed a tutorial to set up my settings.py file for allauth so I don't believe there's a problem there.. any ideas? I'm working in 1.11.6 and am new to Django. Thanks in advance. -
Nginx X-Frame-Options config not working
I am trying to set up an iframe to my application that can be used on all websites. I went into my Nginix configuration on my Linode server 'etc/nginix/nginix.conf/' http { add_header X-Frame-Options "ALLOW-FROM http://website.com"; } ^ That is just a snippet from my global nginix configuration. However when I try and put the iframe on 'website.com' it doesn't work giving me the usual error Refused to display 'http://website.com/#/ft-iframe/' in a frame because it set 'X-Frame-Options' to 'sameorigin Is there an option to tell X-Frame-Options to allow all websites? I've read that if there is no X-Frame-Options header is specified, than by default it will allow all websites access, but this doesn't seem to be the case. The application is Django on the backend, and Angular on the front end. I'm not really sure this matters, but I just wanted to note that. -
Django OneToOneField with possible blank field
Working with Django 1.11 and a postgreSQL Database (just switched from sqlite and didn't have this problem before) So I have 3 models: models.py class Person(models.Model): is_parent = models.BooleanField() class VideoGamePurchase(models.Model): bought_by = models.ForeignKey(Person) after_homework = models.OneToOneField(HomeWork, OPTIONS???) class HomeWork(models.Model): done_by = models.ForeignKey(Person) content = models.CharField(blablaba) So the logic I'm try to implement is that if Person.is_parent is True a VideoGamePurchase instance can be created with an empty or null field for after_homework. However, if Person.is_parent is False, I want this field to be the primary key of a unique HomeWork object. I can't find the right options to achieve this: If I don't have primary_key=True then the makemigrations fails: You are trying to add a non-nullable field 'id' to video_game_purchase without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py so I guess I hav to have primary_key=True. But then it seems like I can't have null=Trueor blank=True. Is there a way to have a OneToOneField optionally empty with postgreSQL? … -
generate a Django-REST-API directly ?
I have already a database that contains 100 tables. Now, I would like to expose it as a REST-API. I've done this before so I am familiar with the procedure. I create a serializer for the model, a ViewSet for the Serialiizer and an a router. I test it on 2 tables and it works. The problem is that I want to expose all my 100 tables. And doing the same prcedure 100 times is no fun. Is there a way to do it only one time? -
i am trying to install django-allauth and i am getting below error on mac
I am getting below error. i need help to resolved this. Using cached django-allauth-0.34.0.tar.gz Collecting Django>=1.8 (from django-allauth) Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File > "<string>" , line 1, in <module> File > "/private/var/folders/br/56_l2gp52_d7zcv_tqyf_fkw0000gn/T/pip-`build-IeTRWv/Django/setup.py"` line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache( ) enter code hereAttributeError: 'module' object has no attribute 'lru_cache' **---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/br/56_l2gp52_d7zcv_tqyf_fkw0000gn/T/pip-build-IeTRWv/Django/** -
How to correct set generic relation?
class A(models.Model): relation = GenericRelation('B') another_relation = GenericRelation('B') class B(models.Model): content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content = GenericForeignKey('content_type', 'object_id') a = A() b = B() How to set connection so that I get b as result of a.another_relation.all()? -
Django Channels Chat Application with Angular Frontend
What is the best way integrated Django channel with latest angular frontend? I need to build a private chat app where user able to send a message and attached image to another user. Messages will contain in inbox and user inbox will show with user image thumbnail text area and last timestamp. Will I send each data with routing.py or I will use URLs.py also? Thanks. -
InterfaceError: Error binding Parameter 5...Django JWT token (django request token tool)
I am trying to set up a "one time use" link creating system with this tool: https://github.com/yunojuno/django-request-token I have followed the instructions on the installation and implementation. Now the implementation says that I should create a Requesttoken in the admin interface or with some other method. When I go to the admin interface and when I go to add the token, I fill out the scope field which is the only one required and click save. This is where I get the InterfaceError:r: Error binding Parameter 5 - probably unsupported type And the error seems to happen at this line of code: super(RequestToken, self).save(*args, **kwargs) Now I will include the models.py file: https://github.com/yunojuno/django-request-token/blob/master/request_token/models.py This is the file which contains the line of code which is causing the error. I am really stuck on this and I hope someone will know how to fix it. If you dont know how to fix the problem maybe you know some tool which does a simillar thing as this one. Thanks in advance -
Django RF docs displaying input fields for POST/PUT requests
I am using DRF Docs (http://drfdocs.com/) to test my API built with Django RF. I have a following URL: url(r'^libraries/$', library_list), And corresponding view: # Get all libraries and create a library @api_view(['GET', 'POST']) def library_list(request): """ List all libraries, or create a new library for a specific user """ if request.method == 'GET': libraries = Library.objects.filter() serializer = LibrarySerializer(libraries, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = LibrarianSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) Model: class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) city = models.CharField(max_length=30) address = models.CharField(max_length=80) phone = models.CharField(max_length=30, blank=True, null=True) website = models.CharField(max_length=60, blank=True, null=True) #This helps to print in admin interface def __str__(self): return u"%s" % (self.name) Serializer: class LibrarySerializer(serializers.ModelSerializer): class Meta: model = Library fields = '__all__' See following image: What exactly am I missing to add (to the view/models/serializer) that the form to POST data is missing? -
error: 'projectname' appears as both a file and as a directory
I have a Django project that I am trying to push (from git repo to server) name of the project is: projectname the account name is gitlab.com/projectname/django I am getting this error when I try to push: error: 'projectname' appears as both a file and as a directory enter code here`error: projectname: cannot drop to stage #0 enter code here`error: Pull is not possible because you have unmerged files. hint: Fix them up in the work tree, and then use 'git add/rm <file>' hint: as appropriate to mark resolution and make a commit. fatal: Exiting because of an unresolved conflict. -
Unable to import view from different app
I'm trying to import a view from one app into another app but it's giving me this error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/trie/Desktop/django/venv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 673, in exec_module File "<frozen importlib._bootstrap>", line 222, … -
Getting this error in django "login() missing 1 required positional argument: 'user' "
I am a new Django user and I just created a registration and login system for my website in Django 1.11. I am struck when I go to login section of my website. I get the error as mentioned "login() missing 1 required positional argument: 'user'" and I can't figure out what's wrong with the login function and the variable 'user'. Kindly help me. Thanks in advance. Here is my code: urls.py: from django.conf.urls import url from . import views from django.contrib.auth import login app_name='one' urlpatterns = [ url(r'^games$',views.games,name='games'), url(r'^others$',views.others,name='others'), url(r'^about$',views.about,name='about'), url(r'^upload$',views.UploadFile.as_view(),name='upload'), url(r'^register$',views.UserFormView.as_view(),name='register'), url(r'^login/$', login, name='login'), ] views.py: from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login from django.views.generic.edit import CreateView from .models import file from django.views.generic import View from .forms import user_form class UserFormView(View): form_class = user_form template_name = 'one/register_form.html' def get (self,request): form = self.form_class(None) return render(request,self.template_name,{'form':form}) def post (self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit = False) username= form.cleaned_data['username'] password= form.cleaned_data['password'] user.set_password(password) user.save() user= authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) redirect('one:profile') return render(request,self.template_name,{'form':form}) -
Django Admin - Sending full QuerySet data in template POST
I'm trying to display a bunch of values from a queryset, have the user select some, and then click submit so I can process those values. However, despite the view on the admin page showing the full data, in the request.POST, I only get the key, and not the value. Concretely: My form field: class ResponseListForm(django.forms.Form): responses = django.forms.ModelMultipleChoiceField( queryset=qs, label="Responses to pick from", help_text="List of completed and deleted responses for the selected project", widget=django.forms.CheckboxSelectMultiple) where qs = Response.objects.filter(project_id=proj_id).values("response_id") In the admin page view, I see: {'response_id': 'id_string'} which is great but when I click submit and check the request body, I only see the response_id and not the id itself: (pdb) request.POST <QueryDict: {'responses': ["['response_id']"]}> Any idea what I'm doing wrong? How can I pass the whole value into the request. Many thanks! -
How To register signals in django?
I am developing a Django app 1.11 i want to email should send after user registration, so I decide to use signals for send email, now when i trying to connect/register the signal with appropriate modal by ready in application configuration class. but I am getting error like follow django.core.exceptions.ImproperlyConfigured: Cannot import 'common'. Check that 'apps.common.apps.CommonConfig.name' is correct. My project folder Structure Looks like /myproject /myproject /apps /common /configs /settings /static /templates Installed Apps Looks Like Follow INSTALLED_APPS = [ 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'rest_framework', 'apps.common.apps.CommonConfig',] and my apps\common\apps.py looks like follow ` from django.apps import AppConfig class CommonConfig(AppConfig): name = "common" ` What Mistake i made here, how to register the signal with django? -
django UserProfile and RegistrationProfile : Same model or different
So i am making a website which requires me to register a user and ask for their email and username and verify the email.After that i ask them to fill a Profile form with information such as name,age,sex,image etc. So should i go about creating seperate models for UserProfile and RegistrationProfile or make it in same model -
django-background-tasks BACKGROUND_TASK_RUN_ASYNC isn't working?
I use django-background-tasks with my Django project, the tasks check on certain files with sleep and take action as a file appears. Everything is working fine but I want the tasks to be executed asynchronously so that missing one file will not lock up everything else, so I went into setting.py to add BACKGROUND_TASK_RUN_ASYNC = True Looks like django-background-tasks just stop executing any task. Once I set: BACKGROUND_TASK_RUN_ASYNC = False it starts executing, synchronously... What am I missing? Thank you. -
Django ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module
I have an almost fresh install of django and it is is giving me this error: ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module. When I try to python manage.py runserver. settings.py WSGI_APPLICATION = 'myproject.wsgi.appli wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() -
Django - AttributeError: Manager isn't accessible via ManagerLog instances
Soy nuevo en python, actualmente estoy desarrollando una aplicación, la cual se encarga de generar varios reportes muy sencillos, sin embargo hay un reporte el cual no he podido resolver aun, he investigado pero aun no consigo la solución. Básicamente lo que quiero realizar es la siguiente consulta SQL a través del ORM: select log.* from file_managerfiles as file, log_managerlog as log where log.fileLog_id = file.id and file.lastUpload = TRUE los modelos son los siguientes: class ManagerFiles(models.Model): filesUpload = models.FileField(upload_to='log', unique=True) processingStatus = models.BooleanField(default=False) lastUpload = models.BooleanField(default=True) class ManagerLog(models.Model): date = models.CharField(max_length=10) time = models.CharField(max_length=30) serialNumber = models.CharField(max_length=30) sessionID = models.CharField(max_length=50) moduleName = models.CharField(max_length=50) operationName = models.CharField(max_length=100) operationSpecific = models.TextField(max_length=500) fileLog = models.ForeignKey(ManagerFiles) Dentro del ultimo modelo (ManagerLog) cree un método que retorna todos los registros del modelo ManagerLog donde ManagerFile.lastUpload sea igual a TRUE: # Report Last Upload File def report_last_upload(self): return self.__class__.objects.filter(ManagerFiles__lastUpload=True) Sin embargo al llamar este metedo (report_last_upload) en mi vista, obtengo el siguiente error: raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__) AttributeError: Manager isn't accessible via ManagerLog instances No entiendo cual es el problema, espero me puedan ayudar, y de antemano gracias. -
regular expression in django blogs.html file error
Can anyone trouble shoot the error in the following code: Code: (in the blog.html file, that is in the blog app) 1 {% extends "aboutme/header.html" %} 2 3 {%block content %} 4 {% for post in object_list %} 5 <h5>{{post.date|date:Y-m-d"}}<a href="/blog/{{post.id}}">{{post.title}}</a></h5> 6 {% end for %} 7 {% endblock %} Error on running: http://127.0.0.1:8000/blog/ TemplateSyntaxError at /blog/ Could not parse the remainder: '-m-d"' from 'post.date|date:Y-m-d"' Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 2.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '-m-d"' from 'post.date|date:Y-m-d"' Exception Location: C:\Python34\lib\site-packages\django\template\base.py in __init__, line 668 Python Executable: C:\Python34\python.exe Python Version: 3.4.3 Python Path: ['C:\\Users\\User\\Desktop\\pythonsite\\mysite', 'C:\\windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages'] Server time: Wed, 13 Dec 2017 19:13:00 +0000 Error during template rendering In template C:\Users\User\Desktop\pythonsite\mysite\blog\templates\blog\blog.html, error at line 5 Could not parse the remainder: '-m-d"' from 'post.date|date:Y-m-d"' 1 {% extends "aboutme/header.html" %} 2 3 {%block content %} 4 {% for post in object_list %} 5 <h5>{{post.date|date:Y-m-d"}}<a href="/blog/{{post.id}}">{{post.title}}</a></h5> 6 {% end for %} 7 {% endblock %} -
Cannot save page with inline model inherited from a mixin
I created a reusable abstract model (mixin) which includes required fields (without blank=True). Then added to a page model inline model which inherits that mixin. Finally I cannot save a page despite I filled in all the required fields. My app crashes with a message those fields cannot be blank. When I eliminate required option everything works well. The same thing if I use this model obviously (as pure inline model, not a mixin) with required fields. What's wrong here? If my approach is quite complicated, what is a better way to reuse code in this case? Mixin: class ContentSectionOneMixin(models.Model): class Meta: abstract = True content_section_one_title = models.TextField(_('Title'), null=True) content_section_one_body = RichTextField(_('Lead'), null=True) content_section_button_caption = RichTextField( _('Caption'), null=True, blank=True ) content_panels = [ MultiFieldPanel( heading=_('Content Section One'), children=[ FieldPanel('content_section_one_title'), FieldPanel('content_section_one_body'), FieldPanel('content_section_button_caption'), ], classname='collapsible collapsed' ), ] Inline model class HomePageContentFlow(Orderable, ContentSectionOneMixin): page = ParentalKey('HomePage', related_name='content_flow') panels = ContentSectionOneMixin.content_panels -
(django) [Errno 11001] getaddrinfo failed
whats wrong with my code? in settings.py EMAIL_HOST = 'smtp.mail.********.info' EMAIL_HOST_USER = 'mail@*********.info' EMAIL_HOST_PASSWORD = '*********' EMAIL_PORT = 465 EMAIL_USE_TLS = True CORS_ORIGIN_ALLOW_ALL=True APPEND_SLASH= False in views.py send_mail('hello', 'pesanan.', 'noreply@server.info', ['arnoldfox21@gmail.com']) I get the following error message [Errno 11001] getaddrinfo failed -
How to make multiple join the Django query
I am new to Django platform. I have a situation where I need to show the data on a page where the table has multiple foreign key columns like status, Priority and task type.when I save the date it saves the ID from the Foreign key table like StatusTable, PriorityTable and TaskTypeTable.The save is working fine as expected.But when I retrieve the date from the table it's giving only the ID not the name. How can i achieve this in Django? Modle.py class StatusTable(models.Model): status = models.CharField(max_length=20,default='') def __str__(self): return self.status class PriorityTable(models.Model): priority = models.CharField(max_length=20,default='') def __str__(self): return self.priority class TeamTable(models.Model): team = models.CharField(max_length=20,default='') def __str__(self): return self.team class TaskTypeTable(models.Model): tasktype = models.CharField(max_length=30,default='') def __str__(self): return self.tasktype class DatacenterTable(models.Model): datacenter = models.CharField(max_length=10,default='') def __str__(self): return self.datacenter class TaskMaster(models.Model): sid = models.CharField(max_length=3) processor = models.ForeignKey(User,null=True) tasktype = models.ForeignKey(TaskTypeTable, null=True) task_title = models.TextField(null=True) task_description = models.TextField(null=True) datacenter = models.ForeignKey(DatacenterTable,null=True) priority = models.OneToOneField(PriorityTable, null=True) status = models.ForeignKey(StatusTable, null=True) pid = models.IntegerField(null=True) sourceincident = models.URLField(null=True) errorincident = models.URLField(null=True) processingteam = models.ForeignKey(TeamTable, null=True) createddate = models.DateField(("Date"), default=datetime.date.today) duedate = models.DateField(("Date"), default=datetime.date.today) istaskactive = models.BooleanField(default=True) forms.py class CreateTaskMaster(forms.Form): sid = forms.CharField(required=False,widget=forms.TextInput(attrs={'class': 'form-control mr-sm-2', 'placeholder': 'SID'})) tasktype_query = TaskTypeTable.objects.values_list('tasktype', flat=True).distinct() tasktype_query_choices = [('', 'Select TaskType')] + … -
Static File in HTML gets distorted when implemented in pythonanywhere server
Hello my question is about why the formatting language of my static file resource gets twisted when rendering. The thing that gets affected the most is spanish special characters like: 'ó' or 'ñ'. For instance: Indicadores de Gestión para Ciudad de México en el Mes de Noviembre 2017. Gets rendered like this: Indicadores de Gestión para Ciudad de México en el Mes de Noviembre 2017. I am using Django 1.11 and my app is hosted in pythonanywhere. Thank you. -
PyCharm does not support Django
I have PyCharm Community Edition 2017. I'm learning django. My PyCharm does not autocomplete django methods and in templates I dont have formatting. Why application for python does not support this ? Is this only for $$$ in PyCharm ??