Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering on the basis of tags in Django Rest Framework
I have an array of tags as a model field, I want to filter out based on those array elements. here is the model in which tag field is an array type I guess. class Mineral(models.Model): name=models.CharField(max_length=500) tags=TaggableManager() def __unicode__(self): return self.name Now in my view, I want to filter out based on this tag field I can do that using Django way like this class MineralList(APIView): queryset = Mineral.objects.all() serializer_class = MineralSerializer permission_classes = [AllowAny] def get(self, request, format=None): mineral = Mineral.objects.all() tags = request.query_params.get('tags', None) name= request.query_params.get('name',None) if tags is not None: tags = tags.split(',') mineral = mineral.filter(tags__name__in=tags).distinct() if name: mineral = mineral.filter(name=name) serializer = MineralSerializer(mineral, many=True) return Response(serializer.data) How can I do that in REST way using filter backends and Filter class -
Default value for a field, based on another field's value
How can I define the default for a Django model field, to be based on the value of another field on the same instance? I want to define a code for the model based on the created timestamp: from django.db import models class LoremIpsum(models.Model): code = models.CharField( max_length=100, default=( lambda x: "LOREM-{0.created:%Y%m%d-%H%M%S}".format(x)), ) created = models.DateTimeField( auto_now_add=True, ) That doesn't work because the function defined for default receives no argument. How can I define a default for the code field such that it is derived from that instance's created field value? -
Django custom template tag throwing an error
I am trying to use a custom template tag and it gives me this error when I am trying to get a rendered page: Invalid block tag on line 29: 'get_message_print_tag', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I am trying to get a simple title for my flash messages based on {{message.tags}} and make it bold in my template. Where am I making a mistake? apptags.py: from django import template register = template.Library() def get_message_print_tag(value): '''return a string for a message tag depending on the message tag that can be displayed bold on the flash message''' if 'danger' in value.lower(): return 'ERROR' elif 'success' in value.lower(): return 'SUCCESS' else: return 'NOTE' html: {% load apptags %} <div class="bootstrap-iso"> {% if messages %} <div class="messages "> {% for message in messages %} <div {% if message.tags %} class="alert {{ message.tags }} alert-dismissible" role="alert" {% endif %}> {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Error: {% endif %} <strong> {% get_message_print_tag {{message.tags}} %} </strong> {{ message }} <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> </div> {% endfor %} </div> {% endif %} </div> -
Store numpy array in session (Alternatives)
I have a class in a view that does some calculations. The instance of this class is passed to a Django template context and the results are displayed in the html. On the other hand, I need to store these results somewhere for later use in another view, where a pdf document is generated using these results. The results are large lists of data. For example: def view_one(request): # some code class_instance = SomeClass(form.cleaned_data) html = render_to_string('results.html', {'instance': class_instance}) return JsonResponse({"result": html}) def view_two(request): # some code class_pdf = GeneratePdf(class_instance) # How can I pass the class_instance data? # some code The results are large lists of data. Should I use Django request session to store the data? Can I use Celery? There is another alternative? -
apache does not pass request to Django (404 not found)
I have a custom 404 page setup for the site, which works fine, like this: when I hit mysite.com/fdsafsadfdsa which doesn't exist, the custom 404 page shows up. However if I add a urlencoded '/' which is '%2f' at the end of url, mysite.com/fdsafsadfdsa%2f, and this gives me the apache 404 not found. it looks like apache decided to handle this 404 itself instead of passing down to Django Anybody has idea why this is happening? -
How to force 'django.contrib.sites' to be migrated first?
When using python manage.py makemigrations on a project that uses functions from the django.contrib.sites, I always received the error: django.db.utils.OperationalError: no such table: django_site. If I comment out the parts of my code that use app, and run makemigrations it works, and then I can uncomment. This (bad) approach works, but I would like to make it work correctly. I already put this app in the top of settings.INSTALLED_APPS, but it does not solve it. -
Adding charaters to a string in specified places - Django
I have a simple python action that I want to take. I have a string. something like 2364968438. I want to take that string that I have and add a - between specific places in the string to make it look like a phone number. something like this 236-496-8438 within my django/python project. I know i am going to have to splice the string into parts but I am having trouble with it. Does it matter if it is a string or integer? -
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?