Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
How to add variable from request.session to each model save() in django
I developed an app in which each user can start his own project and store data. Several users can join the same project. I have created a simple model that holds data for each of these projects. The pk of these projects is added via a middleware to the users request.session object (A user can be part of many projects, but just be logged into a project one at a time.) Now my code is becoming fairly large and complex and I am very often running into problems when saving objects. Either I forget to add the project, or when displaying things I forget to filter by project_id. What would be the best way to handle this when saving objects? I wanted to override the save() on a base class for each of my objects to add the project_id, but I do not have access to the request in my models.py. People discourage sending the request object to models.py. I am also not sure if pre_save can help in any way? Any suggestions on how to handle session variables when saving objects? views.py: obj = Model(project=Project.objects.get(id=self.request.session['authority']), name=obj_name) obj.save() models.py: class Project(models.Model): name = models.CharField(max_length=100) description = models.TextField() class Model(models.Model): name … -
Django and Python Script Integration :(
On my site I have some buttons that when clicked I want them to launch my python script which reaches out to some of my servers and writes to a file. I see plenty of posts online that say its easy but none actually give you steps as to what needs to be done I have a basic html page and the button section looks like the below <td><a href="javascript:alert('Working on it!');"<button type="button" id="myButton1" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off">DO IT</button> If someone could tell me how I can get the DO IT button to launch my .py i would be forever grateful -
Passing a message from context processor to 400 error page
I have a couple of context processors which (for example) check in the admin section if the IP address of the user is allowed. If it's not, I want to raise a PermissionDenied (or SuspiciousOperation) exception. I have already set up basic templates under a template directory in the root of the project (at the same level as manage.py): 400.html, 403.html etc. Within these templates I am using the messages framework to capture any messages sent by the context processors when a user is denied access. Despite setting messages.error(request,'You are not allowed to view the admin for this site') The messages variable is not available to me in any of the error templates. However, if I change the code so my IP address is allowed in, and navigate the admin page, all of the messages are visible. What I really want to do is pass the message when I raise the exception raise PermissionDenied('some message here') But that doesn't work with the 400 templates either, so this is why I resorted to using the messages framework. Am I doing something wrong here? Many thanks -
Django get_or_create returns MultipleObjectsReturned
I am using a model which looks like this : class Box(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) item = models.ForeignKey(Item, related_name="item", null=True) @staticmethod def instance_from_data(data): if len(data) < 2: return None the_item, created = Item.objects.get_or_create(name=data[1]) new_box, created = Box.objects.get_or_create(name=data[0], item=the_item) return new_box Here's an example set of data I'm iterating over: [ [ "Blue box", "Keyboard" ], [ "Red box", "Bottle" ], [ "Yellow box", "Swatch" ], ... ] As the static method instance_from_data is the only place I am creating Boxes, I did not expect to have the error get() returned more than one Box -- it returned 2! Does anyone know how can this be possible ? -
Any one of the field should not be null in Django
I have a post model Which allows users to post Caption(text) image video gif audio or all of them My question is what if they want to post an audio clip without caption or video without a caption or a photo without a video how do I make them post at least one thing thing Because I can't make all fields null or not null -
Django: Implementation Advice: Categories and Product Specifications
I have Product and Categories. A product can be in multiple categories and off course a Category have multiple products. The Categories can have Subcategories’ which can have Subcategories. I used a Category Model with a circular Foreign Key. Each Product can have specifications/attributes based in which Categories is. So the specifications are of the products but depends on the Categories. I can’t add the specifications as Products attributes because they depend on categories, and the user can change categories. I can’t add them as attributes per Category because the value are/can be different for each product. Also an attribute/specification can appear in multiple Categories. I want also to search for a Product filtering by attributes. I think I need a separate Attribute Model that is linked (foreign key) to both Product and Category. Also a way of “protection” in case a Product change categories, a Product and/or a Category is deleted. What is the optimal approach as flexibility and performance ?