Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-mama-cas and django-cas-ng: NotImplementedError
I'm developing a SSO project with django-mama-cas and django-cas-ng. I've followed the installation requirements for each package, and followed this article: https://medium.com/@adiletmaratov/central-authentication-service-cas-implementation-using-django-microservices-70c4c50d5b6f. I'm getting the following error: NotImplementedError: mama_cas.services.backends.SettingsBackend.service_allowed() not implemented Any ideas of what is the cause? -
Django / duplicate key value violates unique constraint
I try to extend django auth user model with OneToOneField but couldn't solve this problem. duplicate key value violates unique constraint "users_profile_user_id_key" DETAIL: Key (user_id)=(67) already exists. I look through this issue , some people say the db out of sync. views.py def create_profile(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = UserProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): registration = user_form.save() profile = profile_form.save(commit=False) profile.user = registration profile.save() return redirect('index') else: user_form = UserRegistrationForm() profile_form = UserProfileForm() return render(request, 'registration/registration.html', {'user_form': user_form, 'profile_form': profile_form}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_image = models.ImageField(upload_to="blog/assets", default="blog/assets/people-photo.jpg", null=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class UserRegistrationForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password') widgets = { 'password': forms.PasswordInput(), } class UserProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('user_image', 'birth_date',) -
User.py Exception Type: TypeError Exception Value: 'Manager' object is not iterable
Hello I have a little problem in Django, I created a database and now I want to print the queries of this, so I have in my user.py file the following code def user(request): user_list = User.objects user_dict = {'user_data': user_list} return render(request,'AppTwo/User.html',context=user_dict) here i get the following error: User.py Exception Type: TypeError Exception Value: 'Manager' object is not iterable. To fix this, I need to change the code to this: def user(request): user_list = User.objects.order_by('first_name') user_dict = {'user_data': user_list} return render(request,'AppTwo/User.html',context=user_dict) but I can not understand why the simple adding of order_by('first_name'), casts the object to a list? Why do I need this? I have trouble to understand, maybe somebody could help me and explain to me what is happening here. Thank you very much in advance -
Python starting two instances of webview when using multithreading with django
import os from threading import Thread import webview def start_backend(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_great_app.settings") from django.core.management import call_command from django.core.wsgi import get_wsgi_application application = get_wsgi_application() call_command('runserver', '127.0.0.1:8080') def start_frontend(): webview.create_window("web app", "http://127.0.0.1:8080/") if __name__ == "__main__": backend_thread = Thread(target = start_backend) backend_thread.start() start_frontend() In this simple examble the webview is started twice, e.g. there are two windows starting after the django server starts. Though I only want one. Does someone know whats incorrect in this code? Tested on Ubuntu and python3.6. -
How do you change the size of permissions boxes in Django Admin section of Authentication and Authorization?
As we know Django has an in-built Admin. I am using it but I cannot seem to get access to its code (perhaps I'm being an idiot, likely,- new to django and inherited an existing project). Crucially, since we are porting a legacy database to this new one there are permissions etc that are assigned to users and groups. As show in the picture below the display boxes for the permissions is too small preventing the administrator from being able to adequately assess the permissions options. How do I change this? -
How can i implement real time notifications in django?
I have read many blogs regarding this but could not understand. Can someone help me in this like what are the different ways of doing it and how to implements this. -
Where does Django build its URLs?
I am playing around with Django and am trying to work through a tutorial for Creating and Running Your First Django Project. My solution is and will remain self hosted at Atlantis-Zero using Aprelium's Abyss Web Server X1. The server has seen set to reverse proxy 127.0.0.1:8000 where the Django development server is running, and the virtual location on the server is DjangoHelloWorld. When trying to access the admin application and viewing the page source, code like the following comes up: <!DOCTYPE html> <html lang="en-us" > <head> <title>Log in | Django site admin</title> <link rel="stylesheet" type="text/css" href="/static/admin/css/base.css" /> <link rel="stylesheet" type="text/css" href="/static/admin/css/login.css" /> <meta name="robots" content="NONE,NOARCHIVE" /> </head> ... Where are URLs globally generated within Django? Either I need to modify how they are being created so that /DjangoHelloWorld/ is part of the path to expected resources, or I need to change some setting so that the development server realizes that it is not at the root of the web site. -
Django Model - Abstract Class with Self Relationship
I'm trying to design a forum thread in Django. Users can post threads, replies to threads, or replies to other thread replies (like in Reddit comments). All posts share basic info like the date and author so I thought I'd make an abstract Post class. Since all posts can have a parent post which they are replying to, my intuition was to try and define it on the abstract class: class Post(models.Model): content = models.TextField(max_length=1000) parent = models.ForeignKey('self', null=True) createdBy = models.ForeignKey(User) class Meta: abstract = True class Thread(Post): title = models.CharField(max_length=200) class ThreadReply(Post): score = models.IntegerField(default=0) But the result is that the child class can only have a parent of the same type, while a ThreadReply should really be able to have a parent that is a Thread OR a parent that is a ThreadReply. One solution is if I define both relationships in ThreadReply: class Post(models.Model): content = models.TextField(max_length=1000) createdBy = models.ForeignKey(User) class Meta: abstract = True class Thread(Post): title = models.CharField(max_length=200) class ThreadReply(Post): score = models.IntegerField(default=0) parentThread = models.ForeignKey(Thread,null=True) parentReply = models.ForeignKey(ThreadReply,null=True) But that doesn't feel...object-oriented enough? It bothers me that every ThreadReply object will have one wasted relationship, as functionally it can only be a replying … -
django template import url tags is there a better way?
My goal is to list a few links in a page and I was wondering if there's a better way of do this line of code: <a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a> This part : ''|add:app_name|add:':'|add:model_name|add:post_fix -- If so, what is the flaw in my thinking, is it the URL-name, or doing too much in the template, or something else? Should I do the construction in python code in view.py, if so can you show me how you would tackle this problem? a_template.html {% for model_name in list_model_names%} .... <a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a> .... {% endfor %} url.py from django.conf.urls import url from . import views app_name = 'app' urlpatterns = [ url(r'^stone/$, view.....as_view(), name='stone_index'), url(r'^cloud/$', view.....as_view(), name='cloud_index'), ] views.py from django.shortcuts import render_to_response from django.views import View class ThisView(View): template_name = 'app/a_template.html' model_names = ['stone', 'cloud'] app_name = 'app' post_fix = '_index' dict_to_template = {'app_name': app_name, 'list_model_name': model_names, 'post_fix': post_fix} def get(self, *args, **kwargs): return render_to_response(self.template_name, self.dict_to_template) Thank you for your time. -
Checking current user against page they are looking at
I am trying to check the currently logged in user against the user who created the page they are looking at. So essentially, if I am logged in I shouldn't able to go to another user's posts/profile and be able to edit it simply by typing in the edit url pattern. Here is my view: class UserEditProfileView(LoginRequiredMixin,UpdateView): login_url = '/login/' model = UserProfile fields = [ 'first_name', 'profile_pic', 'location', 'title', 'user_type', 'about', 'website', 'twitter', 'dribbble', 'github' ] template_name_suffix = '_edit_form' def qet_queryset(self,request): current_user = request.user.id url_args = request.resolver_match.kwargs.pk if current_user != url_args: reverse('index') I have the get_queryset function and the if statement inside it to check if the currently logged in user is the owner of the profile they are trying to edit and redirect them if they aren't. However it is not doing anything... How do I go about implementing this? -
What Django TEST_RUNNER supports xunit xml and logging capture?
I'm attempting to set up a new django project, and I've configured TEST_RUNNER in settings.py to be django_nose.NoseTestSuiteRunner. I chose this test runner because it seems to be the only one I can find that has the following features: writes xunit xml test report captures logging/stdout and only displays for failed tests. However I've heard that nose is unmaintained and I'm having a hard time finding a suitable replacement. The standard test runner doesn't capture logging nor writes xunit as far as I'm able to tell (would love to be proven wrong!) I run tests like so: python -m coverage run manage.py test --noinput python -m coverage report --include="app/*" --show-missing --fail-under=100 python -m coverage xml --include="app/*" -o ./reports/coverage.xml With this in settings.py: TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' And this setup.cfg: [nosetests] verbosity=0 with-xunit=1 xunit-file=./reports/xunit.xml logging-clear-handlers=1 The last two lines are the real juicy bits I can't seem to find in other test runners. nose captures the logging and clears other logging handlers (eg, the handler that dumps on stdout) so the test runs output is much cleaner (you only see logging for tests that failed). In other non-django projects I typically use nose2 but django-nose2 project appears to be 6 years old … -
Choice of architecture for exposing CLIPS expert system as web application
I am relative new to developing web applications. I would like your comments and suggestions of improvement for the following architectural considerations. I have developed an expert system ES using CLIPS. Now I am planning to provide this to variety of users from our company as a web application. Before I start with going into greater details I am currently thinking about which technologies should be involved. The goal is that the user of the web app is facing a chat-like animation which guides him to the final result while he or she provides more and more input to the ES. After conducting some research on my own I came up with the following idea In the backend I use PyCLIPS as an Interface between Python and CLIPS Then I use DJANGO for integrating my python code into the web page dynamically altering the chat between user and ES. There is one thing which is particularly still troubling me a lot: How shall I manage many concurrent users? Shall I use one ES with every user having an individual set of facts or shall every user have his or her own instance of the ES? Do you have any other … -
Django is not generating database tables from models
I have my project with some apps. like: MainProject |---- client |----models.py I'm trying to generate the models that I have in my client/models.py The models are like: class Client(models.Model): name = models.TextField() lastname = models.TextField() picture = models.TextField(blank=True, null=True) active = models.BooleanField() created_at = models.DateTimeField() registeredlanguage = models.TextField() id_language = models.ForeignKey('Language', models.DO_NOTHING, db_column='id_language') email = models.TextField() phone = models.TextField(blank=True, null=True) id_gender = models.ForeignKey('Gender', models.DO_NOTHING, db_column='id_gender') birthdate = models.TextField(blank=True, null=True) facebookid = models.BigIntegerField(blank=True, null=True) class Meta: #managed = False db_table = 'client' The models were generated in a previous project (some years ago), and now when I try to generate the tables again, any table is generated. How I can apply the models from my project into my database? # python manage.py showmigrations account (no migrations) admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add api (no migrations) auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length catalog (no migrations) client [ ] 0001_initial Also # python manage.py makemigrations No changes detected # python manage.py makemigrations client No changes detected in app 'client' -
Make Django test case database visible to Celery
When a Django test case runs, it creates an isolated test database so that database writes get rolled back when each test completes. I am trying to create an integration test with Celery, but I can't figure out how to connect Celery to this ephemeral test database. In the naive setup, Objects saved in Django are invisible to Celery and objects saved in Celery persist indefinitely. Here is an example test case: import json from rest_framework.test import APITestCase from myapp.models import MyModel from myapp.util import get_result_from_response class MyTestCase(APITestCase): @classmethod def setUpTestData(cls): # This object is not visible to Celery MyModel(id='test_object').save() def test_celery_integration(self): # This view spawns a Celery task # Task should see MyModel.objects.get(id='test_object'), but can't http_response = self.client.post('/', 'test_data', format='json') result = get_result_from_response(http_response) result.get() # Wait for task to finish before ending test case # Objects saved by Celery task should be deleted, but persist I have two questions: How do make it so that Celery can see the objects that the Django test case? How do I ensure that all objects saved by Celery are automatically rolled back once the test completes? I am willing to manually clean up the objects if doing this automatically is not possible, … -
How do I concatenate 2 strings in Django
I need to show an image of the database, but I need to insert a slash before {{...}} because only then does the file access the static folder. What should I do? -
How to create a Delete an item in DB from a confirmation pop up in Django?
I have built a website that contains a table with posts and a button of delete. When you click on the delete button it shows a pop up and when you click "confirm" it supposed to delete the item. I don't know how to connect the confirm button to the urls.py that deletes my item. What should I add to the class of PostDelete? Should I add something to the HTML? The form is using POST... As you can see I have in comment a few things I tried like post.delete() but neither of them worked well... Please help me, I am very confused and didn't find any guide for confirmation fade option with django :( Thank you! index.html- <button type="button" class="btn btn-info" data-toggle="modal" data-target="#MyModal" href="{% url 'delete_post' server.id %}">Delete <span class="glyphicon glyphicon-trash" </span></button> <button type="button" class="btn btn-info" data-toggle="modal" data-target="#MyModal">Edit <span class="glyphicon glyphicon-pencil" </span></button> <div id ="MyModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <form action="" method="post">{% csrf_token %} <h4>Are you sure you want to delete?</h4> <input type="submit" class="btn btn-danger btn-md" value="Confirm delete"/> <button type="submit" class="btn btn-default" data-dismiss="modal">Cancel</button> </form> </div> </div> views.py - from django.shortcuts import render_to_response from django.shortcuts import render, redirect from django.template … -
Django a good use case
I'm thinking about using Django to create a web application for a CRUD delete application that can validate a user against LDAP Active Directory. The application will display a list of business intelligence applications the user currently has access to, which applications are available to request access to and the user can request other security permissions. After the user sends a request, it will be written to the database as a request. If a user is a approver they'll have another tab to approve or deny access requests, or create their own access level that is provisioned by their approver. I've developed a CRUD RoR application in the past and since Django is like Rails, I figured something like the application above would be easy to do. I'm just wondering if Django is a good use case for something like the above? -
How to register a django model field with any type?
I have built an API With Django REST Framework. On client side I use Angular and I have an class that looks like: export class Property{ id: number; value: any; } The value property can take many variables with many types: string, array or number... How can I save value with my API? from django.db import models class Property(models.Model): value = ? I've looked a bit. I found Django Generic's relations. But I have no idea how to use it. Can you help me? -
Wagtail unit testing: Adding child pages converts them to base type
Trying to create some unit tests for Wagtail and running into the following problem: >> root = FrontPage.add_root(instance=FrontPageFactory.build()) <FrontPage: article0> >> root.add_child(instance=ArticlePageFactory.build()) <ArticlePage: article0> >> root.get_tree() <PageQuerySet [<Page: article0>]> "article0" goes from being type ArticlePage to type Page in the page tree. Is this Page object a reference to the ArticlePage and there's a method I'm not aware of to fetch it, or am I missing something obvious here? In the meantime I've worked around the problem by just storing the added article pages in a separate list, but I'd really like to understand what's going on here. -
figuring out bug with django cookies: not working on server
I have a site that relies on checking if a cookie exists for service_id and if it does checks if you can upload files for service... this works nicely offline but on pushing changes to server it created a bug where even though the cookie can be seen (on the dev console) and I assign the cookie to a context variable which ends up saying None even though I can see the cookie from the dev console. class PictureCreateView(CreateView): model = Picture fields = "__all__" template_name = 'accounts/upload-file.html' def get_context_data(self, **kwargs): context = super(PictureCreateView, self).get_context_data(**kwargs) context['service_id'] = self.request.COOKIES.get('service_id', None) return context any ideas? -
Routing user profiles at the URL hierarchy root
Facebook, GitHub, and Twitter all place user profile URLs at the root of their URL hierarchies, e.g., http://twitter.com/jack. This must be done so that other "system" URLs, like http://twitter.com/search are resolved first, so a user named @search can't hijack part of the site. And if no system URL exists, and no such user profile is found, they must throw a 404. What's the best way to achieve this using Django's URL routing? My current solution is: urlpatterns = [ url(r'^admin/', admin.site.urls), # etc, ..., then this last: url(r'^(?P<username>.+)$', views.view_profile), ] def view_profile(request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404('User does not exist') return HttpResponse(username + ' exists!') In this way, the view_profile view is a catch-all for any URL that isn't handled elsewhere. However, it doesn't seem ideal that it is responsible for throwing a 404 exception if no user exists, I'd rather raise some "wrong route" signal that tells Django's URL router to resume attempting to route the request. This way the 404 is generated by Django the same way as if I did not have the catch-all route. This question asks essentially the same thing, but the solutions involved creating a subpath for the user profile. -
Python/Django CSV reader script running out of memory
I've got a management command which requests an external gziped CSV file then reads and processes each line. Keep getting memory errors. Have simplified the script as shown below however memory usage is still increasing each iteration until a memory exception occurs. items = [9,61,269,307,317,427,496,547,610,802] for item in items: r = requests.get('https://test.com/' + str(item) + '/gzip/') decompressed_data = zlib.decompress(r.content, 16+zlib.MAX_WBITS) reader = csv.DictReader(decompressed_data.splitlines()) next(reader) for line in reader: mem_used = int(memory.memory())/1000000 logger.info("Memory usage: %smb" % mem_used) Why isn't the used memory getting freed for each iteration of the outer loop? -
Django TemplateView vs DetailView
I'm working on an app that has multiple user profile models that OneToOne field to auth.User. For a specific type of profile's dashboard, say VendorSales, is it better practice to write a DetailView that takes the VendorSales ID in the url, or to just use a TemplateView with no url pk's and reference request.user.vendorsales in the template and self.request.user.vendorsales in the context data? -
foreign key only show owner field django
I have two Model class In django restful API: class Titles(models.Model): title_links=models.CharField(max_length=500) created_by=models.ForeignKey(User,null=True) def __str__(self): return '{}'.format(self.title_links) class All(models.Model): created_by=models.ForeignKey(User,null=True) title1=models.ForeignKey(Titles,related_name='title1',blank=True,null=True,limit_choices_to={'created_by': True},) Now in All class In title1 field I want only those titles who is created_by current logged in user . Kindly help . -
Can't launch django per script (CronJob)
I would like to start a script, which is using my Django project with a python script which first starts a virtual environment. FYI The settings file has the same name as the project folder proj. I wrote some kind of a script to start the script like this #!/usr/bin/python # -*- coding: utf-8 -*- activate_this = '/home/myname/virtualenvs/proj/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) import sys import subprocess path = '/home/myname/proj' if path not in sys.path: sys.path.append(path) subprocess.Popen(['python', '/home/myname/proj/ext_scripts/my_django_script.py'] + sys.argv[1:]) The actual script imports like this ... import time import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") django.setup() ... Which returns ImportError: No module named 'proj'