Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO: How to query multiple tables, equal model without looping
I'm looking for a nice way to query(DJANGO) temporal data, which is stored in different tables, but share the same model. Here's an example data model: class myModel(models.Model): x = models.FloatField() class Meta: db_table = "24-01-2017" Now, I could of course loop over the different days, changing _meta.db_table for every iteration, but there should be a way to do this in a single query in DJANGO. This doesn't seem to be it, as DJANGO develops this may be outdated and I don't see anything related in the documentation. How to handle this neatly? Thanks in advance! -
Deploying django app urls.py 502
Default django application on Digital Ocean VPS. I create app python manage.py startapp app General urls.py link to app urls.py. If I create urls.py inside app manually, it all works fine. But If I replace content of app with the content of my localhost app(where urls.py is the same as that which worked) - I receive 502 url error. Urls.py is the same. I deleted content of default app and moved there localhost app content. Syntax is the same, everything is the same, except replacing files. I suggested that it's because of other files, but have no idea why. What is wrong, why? -
Calling Model function in template not working
I'm trying to get the category of a skill in a template. From the post I read, I can't directly get information from a foreign key in a template. Instead, I add a function on CharacterSkill models to get the Skill category Models.py class Character(models.Model): name = models.CharField(max_length=70) class Skill(models.Model): name = models.CharField(max_length=70) cat1 = '01' SKILLSET_CHOICE = ((cat1:'cat1')) skillset_choice = models.CharField( max_length=2, choices = SKILLSET_CHOICE, default='', blank=True, null=True, ) class CharacterSkill(models.Model): character = models.ForeignKey(Character, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE) def skillcategory(self): return Skill.objects.get(id = self.skill).skillset_choice Template skillsetchoice {{item.skillcategory}} But I get an error : Exception Type: TypeError Exception Value: int() argument must be a string or a number, not 'Skill' I tried to inpect value with the shell console where I can get back the category id but when I use it in template, nothing is working Hope you can help me! -
In Django, How to get the currently running app from within a model on another app?
Basically i am trying to use .get_absolute_url() to return dynamic links in relative to the current app running, in other words reverse the model url to a different url based on which app being called. Let me try to explain what i am trying to do by example, We have three apps Blog (serves as a shared data layer, contains models for post, authors ... etc) BloggerWay (serves as a view layer number one, uses the Blog app models to display content in some given layout) TumblrWay (serves as another view layer, again uses the Blog app models to display content in some given layout) My urls.py files goes like ---------- *Project.urls.py* ---------- urlpatterns= [ url('/blogger/', include(BloggerWay.urls.py, namespace='blogger'), url('/tumblr/', include(TumblrWay.urls.py, namespace='tumblr'),] ---------- *BloggerWay.urls.py* ---------- urlpatterns= [ url('/post/(?P<id>\d+)', Blog.as_view(), name='blog'),] ---------- *TumblrWay.urls.py* ---------- urlpatterns= [ url('/post/(?P<id>\d+)', Blog.as_view(), name='blog'),] My question is How can i define .get_absolute_url() method for the Post model so it knows which app we are in and return the correct url to it. example: if in BloggerWay return '/blogger/post' if in TumblrWay return '/tumblr/post' I know that i can use the reverse() function to get the url for a given named pattern and that it accepts a current_app= … -
Show more information about ManyToMany field?
I use django-reversion app in my project. I have modal "Task" with ManyToMany field "comments". In my project I have page with revertions list. And it shows me in comments field id of comments. For example: comments (field_name): [66, 67, 68] (field_value). What the best way to take that id-s and show the comment information (author, text, created) not only id. Is it possible? I am little bit comfused. models.py: @reversion.register() class Task(models.Model): comments = models.ManyToManyField("Comment") class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) views.py: def task_reversions(request, project_code, task_code): project = get_object_or_404(Project, pk=project_code, status='open') task = get_object_or_404(GroupTask, pk=group_task_code) versions = Version.objects.get_for_object(ask) context = { 'project': project, 'task': task, 'versions': versions, } return render(request, 'project/task_reversions.html', context) task_reversions.html: {% for field_name, field_value in version.field_dict.items %} {{ field_name }} {{ field_value }} {% endfor %} -
django form to apply for designed html elements
I hve this html file: <form method='POST'> {% csrf_token %} <input name='foo'/> <button type="submit">submit</button> </form> Now, imagine this form has css atributes behind, I just want a form which would configure some inputs. For an example. The field is required, the min length is 10 chars, etc etc. How could i approach that with Django forms? is the something like: from django import forms class inputform(forms.Form): input_line = forms.CharField(max_length=20, min_length=10, name='foo') how would i apply that to vies.py and how to get errors out to html? Would appreciate your reply. -
Django-admin: TemplateDoesNotExist at /admin/plans/plan/
I'm trying to make Django-plans app work. Everything seems to be working except /admin/plans/plan/ ( /admin/plans/order/, /admin/plans/userplan/ etc. works correctly). When I click on plan in Django-admin it returns: TemplateDoesNotExist at /admin/plans/plan/ I can't figure out why it wouldn't exists. I took a look at django-plans admin.py file and it seems that Plan doesn't have any special template specified. Do you know what's the problem? TRACEBACK Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/plans/plan/ Django Version: 1.10.5 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'authapp', 'presentationapp', 'allauth', 'allauth.account', 'allauth.socialaccount', 'djmoney_rates', 'djmoney', 'api', 'productapp', 'django_extensions', 'mainapp', 'django_tables2', 'engineapp', 'dashboardapp', 'ticketapp', 'celery', 'dbbackup', 'bootstrap3', 'django_filters', 'widget_tweaks', 'cacheapp', 'adminapp', 'djcelery', 'import_export', 'plans', 'request', 'django.contrib.humanize'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'authapp.middleware.BasicAuthMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'request.middleware.RequestMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: C:\Users\Milano\PycharmProjects\DropboxWorkspaces\priceist_workspace\priceist_venv\lib\site-packages\django\contrib\admin\templates\ordered_model\admin\order_controls.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Milano\PycharmProjects\DropboxWorkspaces\priceist_workspace\priceist_venv\lib\site-packages\django\contrib\auth\templates\ordered_model\admin\order_controls.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Milano\Desktop\Projekty\FS Dropbox\Dropbox\priceist\authapp\templates\ordered_model\admin\order_controls.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Milano\Desktop\Projekty\FS Dropbox\Dropbox\priceist\presentationapp\templates\ordered_model\admin\order_controls.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Milano\PycharmProjects\DropboxWorkspaces\priceist_workspace\priceist_venv\lib\site-packages\allauth\templates\ordered_model\admin\order_controls.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Milano\Desktop\Projekty\FS Dropbox\Dropbox\priceist\productapp\templates\ordered_model\admin\order_controls.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Milano\PycharmProjects\DropboxWorkspaces\priceist_workspace\priceist_venv\lib\site-packages\django_extensions\templates\ordered_model\admin\order_controls.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Milano\Desktop\Projekty\FS Dropbox\Dropbox\priceist\mainapp\templates\ordered_model\admin\order_controls.html (Source does not exist) … -
How to subtract two fields in django templates?
Before marking as duplicate to numerous other questions on SO, read. I have three fields, Credit Available, Credit Limit and Credit Balance. I'm getting the values for Credit Limit and Credit Balance from my database. To display Credit Available, I want to do Credit Limit-Credit Balance. I tried doing this from other answers on stackoverflow, but they did not work <tr> <td style="text-align:center">{{ credit.credit_limit|add:"-{{credit.credit_balance}}" }}</td> <td align="center">{{ credit.credit_limit}}</td> <td align="center">{{ credit.credit_balance }}</td> </tr> Can I do this without writing new template tags or using the mathfilter module? -
Middleware catching social auth before classic authentication. How to check if user is socially authenticated?
My problem is that I have a middleware which is checking if user is authenticated before getting access to rest of a website. If not then redirecting to the login page. I got Facebook login working on my website, but it's getting catched by middleware, so user is unable to get an access to my website using social auth. How can I fix my middleware to accept facebook logins? Probably by checking if user is socially authenticated, but unfortunately I don't know how to do this. Please notice that I'm new to python-social-auth, and not specially experienced in Django. EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') path = request.path_info.lstrip('/') url_is_exempt = any(url.match(path) for url in EXEMPT_URLS) if path == reverse('accounts:logout').lstrip('/'): logout(request) #some new condition? if request.user.is_authenticated() and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated() or url_is_exempt: return None else: return redirect(settings.LOGIN_URL) -
How to get oauth2 client app from Django request
I'm using oauth2_provider + rest_framework. I have configured several client applications, and they successfully authenticate and receive access tokens. I would like to have the client app in the request (Eg. request.client). Perhaps I should create some kind of middleware, which sets it, but I'm not sure what is the proper way to do it. Or maybe this functionality is already provided by the oauth2_provider/oauthlib, and I have overlooked it? The client should be set when: a valid access token is provided valid app credentials are provided (like when requesting access token) Python v3.5.3, Django v1.10.6 -
Displaying form errors with django-boostrap3
I am developing a Web application with Django and django-bootstrap 3. I have several forms which get validated and throw an error if something is wrong. However, I don't want django-bootstrap to show the alert messages in the dismissible red alert boxes. Error messages below input fields are sufficient. How do I achieve this? Password change form example: <form class="allign-bottom" method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary"> {% bootstrap_icon "glyphicon glyphicon-refresh" %}&nbsp; Update password </button> {% endbuttons %} </form> Picture example: -
Django Multiple User types in Django 1.9
I want to create a web app in which I will have two different types of users Employee and Employers. They'll have mostly non common fields.How to implement separate registration of both. Currently I have inherited from the User model. models.py class Category(models.Model): cname=models.CharField(max_length=250) def __str__(self): return self.cname class Workplace(User): address=models.TextField(max_length=250) logo=models.ImageField(upload_to=upload_location,null=True,blank=True) wcategory=models.ForeignKey(Category,on_delete=models.CASCADE) class Employee(User): employee_id=models.CharField(max_length=250) eworkplace=models.ForeignKey(Workplace,on_delete=models.CASCADE) -
Migration error in django
enter image description here I am using django first time and i am unable to get what does this error mean .I am creating app url dispatcher and i get this error.I have created saperate urls.py file for my app and put this code in it My main_app code is from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), ] My project url dispatcher code is enter image description here Please figure it out ? [2]: -
Django: Extremely Large Queryset Slow to Execute (non-linear retrieval time)
I am having Django (Oracle backend, cx_Oracle 5.2.1) execute a query that is a very simple select x.y, x.z from x where x.a = 'foo' and x.b = 'bar' Both x.a and x.b are indexed (db_index=True) The page I use calculates summary statistics on various records using Pandas, so the data sizes are quite large. I have one page loading a subset of ~15000 records. This takes ~2 seconds to load The exact same page, when using a different timeframe, but using the same type of query loads ~50000 records. It takes ~30 seconds to load. I've benchmarked performance, and Pandas is not the bottleneck. The simple my_queryset.all().values(('y', 'z')) takes the overwhelming majority of the time (~90%) Is there any reason why this is, or any way to speed it up? Of note, when executing these queries in a database console, they are both very fast. It seems to be the Django ORM that has issues. -
is there a way to encrypt a string in django then decrypt it?
I have been searching though sites and there are lots talking about the usage of hashlib with sha1, sha2, md5 and few others but somehow I can't seem to see there is a way to decrypt any of them in django. I am not trying to set password so using set password wouldn't work. Can someone give me a hand please? Thanks in advance -
Get data from ManytoMany Relationship
I have the following models: class Speaker(models.Model): id_speaker = models.UUIDField(primary_key=True) name = models.TextField() class Session(models.Model): id_session = models.UUIDField(primary_key=True) name = models.TextField() speakers = models.ManyToManyField(Speaker) When I querying Session.objects.all(), I got the next sample data: { "id_session": "UUID", "name": "Example name", "speakers": [ { "id_speaker": "UUID", "name": "John Doe" } ] } As you see, I have the list of speakers of session, now the question is, how I could got the sessions of speaker, an example that how I want: { "id_speaker": "UUID", "name": "John Doe", "sessions": [ { "id_session": "UUID", "name": "Example name" } ] } If you wondering if I use django-rest-framework, the answer is YES. -
Product Model with type and subtypes Django 1.10
Hi all!! What I need is to create a product model wich have multiples types and type have multiples subtypes I will share my models code and please someone tell me if I'm going in a good way. class productCatalog(models.Model): name= models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name def get_absolute_url(self): return reverse("product_detail", kwargs={"id": self.id}) class productType(models.Model): productID = models.ForeignKey(productCatalog) typeName = models.CharField(max_length=200) class product_subType(models.Model): typeID = models.ForeignKey(productType) subType_name = models.CharField(max_length=200, null=False, blank=False) This is the final result that I want to get: Product name Type 1: Sub Type 1 Sub Type 2 Sub Type 3 Type 2: Sub Type 1 Sub Type 2 etc. -
Filter M2MField with extra column
I created a Django 1.10 app with Rest-Framework, I have trouble making any custom field that will yield the date range of a date field in M2MField, i will explain my problem with my code. class FoodConsumption(models.Model): ''' An item consume by animal. ''' animal = models.ForeignKey( Animal, related_name='animal_food_consumptions', on_delete=models.CASCADE) food = models.ForeignKey( Food, related_name='food_consumptions', on_delete=models.CASCADE) date = models.DateField() class FoodConsumptionTransaction(models.Model): herd = models.ForeignKey( Herd, related_name="food_consumption_transactions", on_delete=models.CASCADE ) food_consumptions = models.ManyToManyField(FoodConsumption) And here is my serializer to display the FoodConsumptionTransaction data. class FoodConsumptionTransactionListSerializer(serializers.ModelSerializer): class Meta: model = FoodConsumptionTransaction fields = ['id', 'herd', 'food_consumptions'] Create a couple of FoodConsumption: from dateutil import parser fc1 = FoodConsumption.objects.create( animal=animal_obj_1, food=food_obj_1, date=parser.parse('2017-04-06').date() // min date ) fc2 = FoodConsumption.objects.create( animal=animal_obj_2, food=food_obj_2, date=parser.parse('2017-04-08').date() ) fc3 = FoodConsumption.objects.create( animal=animal_obj_3, food=food_obj_2, date=parser.parse('2017-04-10').date() // max date ) # add to the transaction fc_trans = FoodConsumptionTransaction.objects.create( herd=herd_obj_1 ) fc_trans .food_consumptions.add(fc1, fc2, fc3) Now when getting data of FoodTransaction by herd i get this list: [ { "id": 1, "herd": 1, "food_consumptions": [1, 2, 3], # pks of FoodComsumption } ] But how can i create extra fields based from food_consumptions field , food.date (min and max)? [ { "id": 1, "herd": 1, "food_consumptions": [1, 2, 3], # pks of … -
Get a list of ids from Ajax POST to my django view
I have the following template: <table id="meds"> [...] </table> <div> <button type="button" id="continue"> Continue</button> </div> <div id="message"></div> With the following script: jQuery(document).ready(function($) { $("#continue").click(function() { var selected = $("#meds").bootgrid("getSelectedRows"); console.log(selected); $.ajax({ type: "POST", url: "/prescription/", data: { selected, csrfmiddlewaretoken: "{% csrf_token %}"}, success: function(result) { $('#message').html("<h2>Contact Form Submitted!</h2>") } }); }); }); Since I'm using jQuery Bootgrid I can select the rows I want and get them in the variable $("#meds").bootgrid("getSelectedRows") which I would like to send to my view using Ajax POST like so: views.py class PrescriptionView(generic.ListView): template_name = 'meds/prescription.html' context_object_name = 'meds' model = Medicament def get_context_data(self, request, **kwargs): selected_ids = request.POST context = super(PrescriptionView, self).get_context_data(**kwargs) context.update({'meds': Medicament.objects.get(id__in=selected_ids)}) return context urls.py url(r'^prescription/$', views.PrescriptionView.as_view(), name='prescription'), For some reason even when I click on the continue button which is supposed to take me to the prescription.html page where I have information about the objects with the ids I sent but nothing happens except the console does log the selected ids like so [5, 6] and the error: POST http://127.0.0.1:8000/prescription/ 403 (Forbidden) I can't point out what I'm doing wrong -
Django- Structuring Data Tables
I want to build an app using Django but I am not sure what the best way to structure my data tables would be. Basically, it is a site where teachers can create a class and within the class, create assignments. Then students can join their class and complete the assignments. Thus, I need to keep track of teacher_users, student_users, courses, assignments, and submissions. Thus, my question is how should I structure my data tables? Would it be better to just have the five tables listed and lump everyone's data together and constantly sort and search it every time I need a piece of info or would it be better to create a new set of tables for each teacher that signs up? I have heard that it is bad to create new tables at runtime but it seems like having separate tables for each teacher would prevent a lot of sorting and searching. Or is there a third way that I am missing? Thanks. -
uWSGI equivalent for Django-Channels
I am aware that Django is request/response cycle and Django Channels is different, my question is not about this. We know that uWSGI/gunicorn creates worker processes and can be configured execute each request in threads. So that it can serve 10 requests "concurrently" (not in parallel) in a single uWSGI worker process with 10 threads. Now let's assume that each web client wants to create a websocket using Django Channels, from my limited understanding (with vanilla implementation), that it will process each message in a single thread, which means, to process x amount of connections concurrently, you need x amount of channel worker processes. I know someone will suggest to increase the number of processes, I am not here to debate on this. My question is simply are there any existing libraries that does similar job with uWSGI/gunicorn that execute consumer functions in threads? -
Error in connecting django with mongodb: ImportError: No module named django.auth
I am trying to create a blog using django and mongodb in aws ec2 instance And in the file models.py, I am making following changes from datetime import datetime from mongoengine import * from mongoengine.django.auth import User from django.core.urlresolvers import reverse class Post(Document): user = ReferenceField(User, reverse_delete_rule=CASCADE) title = StringField(max_length=200, required=True) text = StringField(required=True) text_length = IntField() date_modified = DateTimeField(default=datetime.now) is_published = BooleanField() from django.core.urlresolvers import reverse class Post(Document): user = ReferenceField(User, reverse_delete_rule=CASCADE) title = StringField(max_length=200, required=True) text = StringField(required=True) text_length = IntField() date_modified = DateTimeField(default=datetime.now) is_published = BooleanField() def __unicode__(self): return self.title def save(self, *args, **kwargs): self.text_length = len(self.text) return super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('detail', args=[self.id]) def get_edit_url(self): return reverse('update', args=[self.id]) def get_delete_url(self): return reverse('delete', args=[self.id]) And, I get this error Traceback (most recent call last): File "models.py", line 7, in <module> from mongoengine.django.auth import User ImportError: No module named django.auth And, in settings.py file, I am making following changes import os from mongoengine import * PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['54.149.63.203', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'LJblog', 'django_extensions', 'mongoengine.django.mongo_auth', … -
Web Application for data analysis : Which frameworks to use?
I intend to create a web application which would use numpy,scipy and other python libraries to create complicated graphs using data analysis and Machine learning. I have following questions with respect to this: Can I use Django framework for this? If no , which other framework / library can be used for backend Can the frontend be like a Single page application ? Can I use AngularJS if I'm using a using a python backend framework? What would be best combination for effective and fast backend calculations , and smooth and sleek display on the front-end? Please list any alternatives in case I'm missing something -
Django/GraphQL triple join table
I am creating an app that allows users to answer form. So I have : class Form(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) topic = models.CharField(max_length=40) class Question(models.Model): form = models.ForeignKey(Form, on_delete=models.CASCADE) text = models.CharField(max_length=200) question_type = models.CharField(max_length=10) class Participation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) form = models.ForeignKey(Form, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Answer(models.Model): participation = models.ForeignKey(Participation) question = models.ForeignKey(Question) value = models.CharField(max_length=255) where User is a model from django.contrib.auth.models How can I query for all the users who have answered a specific form ? -
Using and Posting results of Sortable in Django
I am making a list of models that I want to be able to drag around, then save the order as their new ordering in the database based off a ordering value attached. Right now I have this code for the html: <script src="https://code.jquery.com/jquery-3.2.1.js"></script> <script src="https://code.jquery.com/ui/3.2.1/jquery-ui.js"></script> <script src="{% static 'draggable.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $("#test").submit(function(event){ $.ajax({ type:"POST", url:"{% url 'editpage' bid=book.id pid=page.page_num %}", data: { 'order': 1 // insert ordering here }, success: function(){ } }); return false; }); }); </script> </head> <body> <h1>{{page.page_title}}</h1> <ul id="sortable"> {% for section in sections.all %} <li style="background:blue">{{section.section_title}}</li> {% endfor %} </ul> <form method='post' id ='test'> <input type='submit' value='Test button'/> </form> The problem I am having is trying to get sortable to work. Where do I insert the script (#sortable).sortable() so that it will work when the page loads and then on press, POST to the view for parsing. My view if it helps: @ensure_csrf_cookie def editpage(request, bid = -1, pid = 1): ret = {} b = Textbook.objects.get(id = int(bid)) page = b.pages.get(page_num = int(pid)) ret = { 'book':b, 'page':page, 'sections':page.sections, } if request.method == 'POST': print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + request.POST.get('order')) return render(request,"content/editpage.html", ret) A good part of this is test code but I …