Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create dropdown-menu from existing dropdown-menu
I'm building my Django website and I have questions about this process : dropdown-menu from BootStrap3. I created dropdown-menu in my navbar and it works perfectly well. But, as I have some tabs, I would like to concatanate someone and get dropdown-menu inside an existing dropdown-menu. I have already this kind of things : With this kind of script (for example Fiches Individuelles tab) : <!-- Individual form tab --> {% if user.is_authenticated %} <li class = "dropdown"> <a href = "accueil" class = "dropdown-toggle" data-toggle = "dropdown"> <span class="glyphicon glyphicon-baby-formula"></span> Fiches Individuelles <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "{% url "home" %}"> Accueil des fiches individuelles </a></li> <li><a href = "{% url "form" %}"> Création des fiches individuelles </a></li> <li><a href = "{% url "searched" %}"> Consultation des fiches individuelles </a></li> <li><a href = "{% url "edited" %}"> Edition des fiches individuelles </a></li> <li><a href = "{% url "deleted" %}"> Suppression des fiches individuelles </a></li> </ul> </li> And now it's a representation from what I want to get finally : I want to get a dropdown-menu from an existing dropdown-menu. I tried to write something : <!-- Resume Tab with acts --> {% … -
Eztables Table Will Not Display
I'm new to Django so please excuse this post if it seems really simple to you. I can't get my template to display the table using Eztables. I'm presented with a KeyError 'iColumns' error. I am using Django 1.10 A cut down version of my Models, URLs, Views and template are shown below. models.py from django.db import models class Inspection(models.Model): inspected_by = models.CharField(max_length=25) date_board_received = models.DateTimeField(null=True) date_board_inspected = models.DateTimeField(auto_now=True) views.py from eztables.views import DatatablesView from pcb_quality_inspection.models import Inspection class ObjectBrowserDatatablesView(DatatablesView): model = Inspection fields = { 'inspected_by': 'inspected_by', 'date_board_received': 'date_board_received', 'date_board_inspected': 'date_board_inspected', } urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'test/$', views.ObjectBrowserDatatablesView.as_view(), name='all_data'), ] test.html {% extends CMS_TEMPLATE %} {% load cms_tags %} {% load static %} {% load js staticfiles eztables %} {% load eztables %} {% load js staticfiles %} {% load js %} {% block server-side %}active{% endblock %} {% block server-side-container %} <head> {% datatables_bootstrap_css %} {% datatables_js %} {% datatables_bootstrap_js %} </head> {% datatables_js %} <table id="abcdef" class="datatable"> <thead> <tr> <th>Inspected By</th> <th>Date Board Received</th> <th>Date Board Inspected</th> </tr> </thead> <tbody> </tbody> </table> <script> $(function(){ $('#abcdef').dataTable({ "bPaginate": true, "sPaginationType": "bootstrap", "bProcessing": true, "bServerSide": true, "sAjaxSource": Django.url('dt-Inspection-objects'), "aoColumns": [ { "mData": … -
not enough values to unpack (expected 2, got 1)
i'm using the following function def loginview(request): template = "../institute.html" uid = request.POST.get('userid') utoken = request.POST.get('usertoken') return render(request, 'search/login.html', {'uid': uid, 'utoken': utoken}) where uid and utoken passed to follwing function, but i'm getting Value error def institute(request): searchText = request.POST.get('instname') uid, utoken = loginview(request) i'm getting the error ValueError: not enough values to unpack (expected 2, got 1) traceback is as follows Traceback (most recent call last): response = get_response(request) response = self.process_exception_by_middleware(e, request) response = wrapped_callback(request, *callback_args, **callback_kwargs) uid, utoken = loginview(request) ValueError: not enough values to unpack (expected 2, got 1) -
Django session delete json object
How can I remove object from session which has 'pk':50 and store it for all pages. I added SESSION_SAVE_EVERY_REQUEST=True to Settings.py and request.session.modified = True to just above line when I modify request session, but there was no effect. Json looks like [ { "pk": 50, "model": "notifications.notification", "fields": { "recipient": 81, "verb": "commented", "emailed": false, "action_object_object_id": "", "level": "info", "deleted": false, "timestamp": "2017-01-25T11:18:53.197Z", "target_content_type": null, "actor_object_id": "1", "action_object_content_type": null, "target_object_id": "790", "actor_content_type": 3, "unread": true, "data": "\"\"", "public": true, "description": "commented on your request" } }, { "pk": 38, "model": "notifications.notification", "fields": { "recipient": 81, "verb": "commented", "emailed": false, "action_object_object_id": "", "level": "info", "deleted": false, "timestamp": "2017-01-24T12:23:08Z", "target_content_type": null, "actor_object_id": "1", "action_object_content_type": null, "target_object_id": "790", "actor_content_type": 3, "unread": true, "data": "\"\"", "public": true, "description": "commented on your request" } } ] -
How to change the GAE to python3? Since i am developing a Django website.
How to change the GAE to python3? Since i am developing a Django website. (How can Google still running python 2.7=_= -
Dango. User permissions for content
I have this problem: News website. There are 2 types of content: Free and Paid. There are 3 types of users: The user (and Guest) and the Subscriber. The user can see free content. And can comment on the content. Guests can see the free content. And Can not comment on the content. The subscriber can see the free and paid content. And can comment on the content. Monthly subscription. Please give excellent solutions. -
return list of ids in a Get. Django Rest Framework
I have a model called "document-detail-sample" and when you call it with a GET, something like this, GET https://url/document-detail-sample/ then you get every "document-detail-sample". Inside the model is the id. So, if you want every Id, you could just "iterate" on the list and ask for the id. Easy. But... the front-end Developers don't want to do it :D they say it's too much work... So, I gotta return the id list. :D I was thinking something like GET https://url/document-detail-sample/id-list But I don't know how to return just a list. I read this post and I know how to get the id_list in the backend. But I don't know what should I implement to just return a list in that url... the view that I have it's pretty easy: class DocumentDetailSampleViewSet(viewsets.ModelViewSet): queryset = DocumentDetailSample.objects.all() serializer_class = DocumentDetailSampleSerializer and the url is so: router.register(r'document-detail-sample', DocumentDetailSampleViewSet) so: 1- is a good Idea do it with an url like .../document-detail-sample/id-list" ? 2- if yes, how can I do it? 3- if not, what should I do then? -
Add restriction to model
Given these two models: PRIMARY, SECONDARY = 0, 1 STORAGE_TYPE = ( (PRIMARY, "Primary"), (SECONDARY, "Secondary"), ) class Storage(models.Model): company = models.ForeignKey(Company, related_name='storage') storage_type = models.PositiveIntegerField(choices=STORAGE_TYPE) class Company(models.Model): name = models.CharField(max_length=64) I want to add a restriction so one Company only may have one Primary storage_type. The rest must be Secondary. What would be the best way to achieve this? -
Ldap Django Authentication with session
I am using an Django-Ldap authentication for my project . I have did the authentication part . I want to maintain session between the user logging in and logout time . How to do it . ? My code is def post(self,request): userData = json.loads(request.body) username = userData.get('username') password = userData.get('password') oLdap = LDAPBackend() try: User = oLdap.authenticate(username=username,password=password) if User is not None: User_Grps = User.ldap_user.group_dns else: User_Grps = "Check your username and password" except Exception as e: User_Grps = "Error" return HttpResponse(User_Grps) How to maintain a session in this and i also want to indicate the client about the session . Thanks -
django migrations - get migrations from location on disk
I have a django project but i want to get the migrations from a different location (not the project itself). I tried to use the MIGRATION_MODULES in the settings page but i could only make it work with different in project modules. I want to be able to do something like this but with paths to the migration files per app. I digged in the migration mechanism in django and found this code that loads the migrations: # part of loader.py from django.db.migrations @classmethod def migrations_module(cls, app_label): if app_label in settings.MIGRATION_MODULES: return settings.MIGRATION_MODULES[app_label] else: app_package_name = apps.get_app_config(app_label).name return '%s.%s' % (app_package_name, MIGRATIONS_MODULE_NAME) def load_disk(self): """ Loads the migrations from all INSTALLED_APPS from disk. """ self.disk_migrations = {} self.unmigrated_apps = set() self.migrated_apps = set() for app_config in apps.get_app_configs(): # Get the migrations module directory module_name = self.migrations_module(app_config.label) was_loaded = module_name in sys.modules try: module = import_module(module_name) except ImportError as e: When i get to my module - it fails on the import_module line. Is there any way to tell django the migration module location on disk instead of the module name? -
Multiple AUTH_USER_MODEL In django
In my Django project (which is a REST API) I'm having a problem that has probably been encountered before yet I can't find a good solution to it anywhere. In my project I have 2 different kinds of users, "Mobile app users" and "Business users". The mobile app users can go into our mobile app and see content around them based on geolocation. The business users can log on to a web admin portal and generate the content that the mobile app user sees. As a caveat there is also the possibility that a business user can also be an app user. I want to be able to allow a business user and an app user to have the same email while still having it be unique to their model. Now Problem is how It is possible to create a two account(1st is mobile app & 2nd is business) with same Email ID.. -
django channels and swift?
I am planning to build an app, which needs some form of communication build in. I am going to use Swift, Python and RestFul API. I am total rookie. Can I use Django Channels and Swift to make "chat" which can be build into to both Swift (for mobile purpose) and Django (for desktop)? -
list index out of range - in shell works
the problem is when I want to take out the value from Models. I type: Food.objects.filter(FoodQuantity__quantity=self.quantity, id=self.id)[0].kcal in shell it works... in application I get error: "list index out of range" -
Celery multiple queues for independence between tasks
This is less so a problem and more about guidance and best practice for celery as I am new to it. I'm looking to use celery to manage tasks that are invoked from web requests in django. My scenario is that I have a continual input stream of such tasks which add or delete rows in my database. Each task is limited in independence based on a parameter that is passed to the task - uid. That is to say, I don't care about tasks with different uids running at the same time, but will run into concurrency issues if multiple tasks with the same uid parameter run at the same time. Trivially I could set up a single worker with --concurrency = 1, but I want to ensure good utilisation of all cores on my system. My thinking was that I could set up a number of different queues (each with --concurrency=1) and then dynamically assign tasks to a a queue based on a hash of the uid - where tasks with the same uids are posted to the same queue. Does this seem like a reasonable set up, and in particular, is the association of a task to … -
Django - how to make temporary (on disk) file from uploaded (memory) file?
I'm working on a project where user uploads a file during creating the order. The file is sent through AJAX to a view and then recognized number of words which returns back. For this purpose, I want to use textract module. The problem is that I haven't found a way how to add an inmemory uploaded file as an textract.process(filepath) argument since it wants filepath, not a file. So I suppose I should save this file temporary on the drive and send a path to this file to process function. @csrf_exempt def ajax_file_word_count(request): from SolutionsForLanguages import word_counter file = request.FILES.get('file') count = word_counter.count_words(file) return JsonResponse({'word_count': count}) How can I do that so the file is immediately deleted after words are counted? -
Django TypeError on every page
I haven't touched the code on my app in weeks but i'm suddenly getting this exact same TypeError on every page, including Admin pages. The last thing to happen was an update on a model to change a ForeignKey field, but I don't feel the two are related Environment: Request Method: GET Request URL: http://10.0.0.161:8001/admin/ Django Version: 1.9.3 Python Version: 2.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phones', 'jobs', 'profiles', 'freelancers', 'stock', 'finance'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'profiles.middleware.UpdateLastActivityMiddleware'] Traceback: File "/Users/studioxag/Documents/repos/telephones/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 174. response = self.process_exception_by_middleware(e, request) File "/Users/studioxag/Documents/repos/telephones/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 172. response = response.render() File "/Users/studioxag/Documents/repos/telephones/lib/python2.7/site-packages/django/template/response.py" in render 160. self.content = self.rendered_content File "/Users/studioxag/Documents/repos/telephones/lib/python2.7/site-packages/django/template/response.py" in rendered_content 137. content = template.render(context, self._request) File "/Users/studioxag/Documents/repos/telephones/lib/python2.7/site-packages/django/template/backends/django.py" in render 95. return self.template.render(context) File "/Users/studioxag/Documents/repos/telephones/lib/python2.7/site-packages/django/template/base.py" in render 204. with context.bind_template(self): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__ 17. return self.gen.next() File "/Users/studioxag/Documents/repos/telephones/lib/python2.7/site-packages/django/template/context.py" in bind_template 260. updates.update(processor(self.request)) Exception Type: TypeError at /admin/ Exception Value: 'NoneType' object is not iterable -
Django - Return foreignkey field in string method
I want to return a foreign key field value as the unicode or string method of another model.. like this.. class Schedule(models.Model): month = models.charField(max_length=20) .... lots more fields here def __str__(self): return related_model.Event.long_name class Event(models.Model): schedule = models.Foreignkey(Schedule) long_name = models.CharField(max_length=100) I'm not sure how to do it, because if the order of the classes is reversed then Event can't have a foreign key to Schedule. What would be the correct way to do this kind of thing? -
How to create a new model object when a user signs up using django all-auth?
When a user registers, I want to create a profile object like this: profile = Profile.objects.create(username=username, points=0, age=0). Django all-auth's register view looks like this: class SignupView(RedirectAuthenticatedUserMixin, CloseableSignupMixin, AjaxCapableProcessFormViewMixin, FormView): template_name = "account/signup." + app_settings.TEMPLATE_EXTENSION form_class = SignupForm redirect_field_name = "next" success_url = '/' @sensitive_post_parameters_m def dispatch(self, request, *args, **kwargs): return super(SignupView, self).dispatch(request, *args, **kwargs) def get_form_class(self): return get_form_class(app_settings.FORMS, 'signup', self.form_class) def get_success_url(self): # Explicitly passed ?next= URL takes precedence ret = ( get_next_redirect_url( self.request, self.redirect_field_name) or self.success_url) return ret def form_valid(self, form): # By assigning the User to a property on the view, we allow subclasses # of SignupView to access the newly created User instance self.user = form.save(self.request) try: return complete_signup( self.request, self.user, app_settings.EMAIL_VERIFICATION, self.get_success_url()) except ImmediateHttpResponse as e: return e.response def get_context_data(self, **kwargs): ret = super(SignupView, self).get_context_data(**kwargs) form = ret['form'] email = self.request.session.get('account_verified_email') email_keys = ['email'] if app_settings.SIGNUP_EMAIL_ENTER_TWICE: email_keys.append('email2') for email_key in email_keys: form.fields[email_key].initial = email login_url = passthrough_next_redirect_url(self.request, reverse("account_login"), self.redirect_field_name) redirect_field_name = self.redirect_field_name redirect_field_value = get_request_param(self.request, redirect_field_name) ret.update({"login_url": login_url, "redirect_field_name": redirect_field_name, "redirect_field_value": redirect_field_value}) return ret Where in this view would I write my object.create code? I find it abit hard to follow how all-auth's code is working hence why i'm asking. Here is my model if … -
module 'app.forms' has no attribute 'JobsFormSet'
I've have something like this in django: "module 'app.forms' has no attribute 'JobsFormSet'" forms.py # -*- coding: utf-8 -*- from django.forms import ModelForm, Textarea from . import models from django.forms.models import inlineformset_factory class CustomerForm(ModelForm): class Meta: model = models.Customer exclude = ('author',) widgets = { 'opis': Textarea(attrs={'rows': 2, 'cols': 80}) } JobsFormSet = inlineformset_factory( parent_model=models.Customer, model=models.Job, max_num=6, min_num=1, validate_max=True, validate_min=True, extra=2, fields=('name', 'isHappy') ) views.py: from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from . import models from . import forms from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.http import HttpResponseRedirect @method_decorator(login_required, 'dispatch') class CustomerCreate(CreateView): model = models.Customer form_class = forms.CustomerForm success_url = reverse_lazy('app:lista') def get_context_data(self, **kwargs): context = super(CustomerCreate, self).get_context_data(**kwargs) if self.request.POST: context['jobs'] = forms.inlineformset_factory(self.request.POST) else: context['jobs'] = forms.JobsFormSet() return context def post(self, request, *args, **kwargs): self.object = None form = self.get_form() jobs = forms.JobsFormSet(self.request.POST) if form.is_valid() and jobs.is_valid(): return self.form_valid(form, jobs) else: return self.form_invalid(form, jobs) def form_valid(self, form, jobs): form.instance.author = self.request.user self.object = form.save() jobs.instance = self.object jobs.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, jobs): return self.render_to_response( self.get_context_data(form=form, jobs=jobs) ) I don't know where is a problem. I'm beginner in django. I'm pretty sure this code is correct, because I'm using from this tutorial (in polish) … -
Django query aggration with on itself join
With the following model, I would like to select root users having the most posts in validated state (in a single query or at least in an optimized way). class User(models.Model): name = models.CharField(max_length=255) # root users have no root root = models.ForeignKey('User', blank=True, null=True) class Post(models.Model): STATE_CHOICES = ( (0, 'Writting'), (1, 'Reviewing'), (2, 'Validated'), (3, 'Published'), (4, 'Removed'), ) state = models.IntegerField(choices=STATE_CHOICES, default=0) author = models.ForeignKey('User') # all validated but not published posts: Post.objects.filter(state=2) # all user having validated but not published posts: User.objects.filter(post__state=2) # same with number of posts User.objects.filter(post__state=2).annotate(post_count=Count('post__author') # same ordered by number of posts User.objects.filter(post__state=2).annotate(post_count=Count('post__author')).order_by('-post_count') # same keeping only the top 10 User.objects.filter(post__state=2).annotate(post_count=Count('post__author')).order_by('-post_count')[:10] # same aggregated for root users: NOT WORKING! User.objects.filter(post__state=2).annotate(post_count=Count('post__author__root')).order_by('-post_count')[:10] -
Primary Key Django Model - PSQL Database
I have a PSQL database with portfolios and their values each day for a few years. I'm using Django to develop a web app behind this. I used this link: https://docs.djangoproject.com/en/1.10/howto/legacy-databases/ to generate the models for Django. I did not explicitly define a primary key in my database or in the models.py file. Is it necessary to define a primary key in order to retrieve data from the DB? If so, is there a way to make multiple fields a primary key? In this case it has to be the portfolio ID and the date, since there are multiple portfolios and dates. Thanks for any help! -
Why Many to Many relationship with self can't be symmetrical
I'm trying to make a model with many to many relationship to itself and this relationship will also have a specific table that will store some information about the relationship, but I'm running into some problems. I tried to make a many to many relationship with diferent models like the Django docs say, and it's worked fine in some other point of my application. But now I tried to do something like this: Let's say that I want a model that represents an object (called Item) that is made by other items and also is used to make some other items. For instance, an object Door is made by wood and lock, but Door will also be used to make a House. I thought in something like this for my models class Item(models.Model): name = models.CharField(max_length=100) items = models.ManyToManyField("self",through='IsMadeBy') class IsMadeBy(models.Model): itemResult = models.ForeignKey('Item', related_name='itemResult') itemPart = models.ForeignKey('Item', related_name='itemPart') amountUsed = models.PositiveIntegerField() I'm getting the error message: Many-to-many fields with intermediate tables must not be symmetrical. So, adding the argument symmetrical=False to my relationship the error stops. With that being said, I want to know how this really works under the hood. For intance, what the symmetrical means in this … -
'UserForm' object has no attribute 'Cleaned_data'
So I just created a form and keep getting this error, why? I correctly use the Cleaned_data after I checked if the form is valid, right? This is my forms.py: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) username = forms.CharField(max_length=10) email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password'] This is my views.py: class UserFormView(View): form_class = UserForm template_name = 'Home/index.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.Cleaned_data['username'] password = form.Cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('Home:Dashboard') return render(request, self.template_name, {'form': form}) There are other topics about this issue but I could not get any help out of them, as most people didn't include the if form.is_valid(), but in my case I do. -
WagtailCMS Multisite Site Configuration
I am building a non profit association website and am using the Sites feature to build custom templates for their chapter sites. What I am trying to do is re-use the templates by targeting the Sites name or id or... For instance, if you look at the screenshot below, I have two sites so far I am testing and I have a model called StandardPage(Page) and a matching template standard_page.html. The main site will look slightly different than the chapter sites, but I would like to re-use the standard_page.html template for both with an if path is this, display this, if not this... I know this isn't correct, but to illustrate what I am trying to do: standard_page.html {% if request.path != '/' %} {% include 'includes/chapter/_chapter-standard-page-content.html' %} {% else %} {% include 'includes/ao/_ao-standard-page-content.html' %} {% endif %} They have over 50 chapters around the world, so you can see how important it would be to be able to re-use templates so I am not having to created each template for each model for each chapter . Thank you. -
the css file doesn't work when in the Django app
when i use static file in my django app,i found a strange problem : that when i use body{ } in the css file can change the body's attributes ,when i use the div's id or class name ,the css file doesn't work on the div's attributes like this: the base.html: <!DOCTYPE html> {% load staticfiles %} <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %} Food {% endblock title %}</title> <link rel="stylesheet" href="{% static "style/index.css" %}" media="screen"/> </head> <body> <div class="sidebar"> {% block sidebar %} {% endblock %} </div> <div class="content"> {% block content %} <i>Delicious</i> {% endblock %} </div> </body> </html> and the index.html: {% extends "blog/base.html" %} {% block title %} Food title{% endblock title %} {% block content %} <div class="body-head"> </div> <div class="body-middle"> </div> <div class="body-foot"> </div> {% endblock content %} the index.css: body { height: 100%; width: 100%; background-color: brown; } .sidebar{ width: 100%; height: 10%; background-color: seagreen; } .body-head { width: 100%; height: 50%; background-color: sandybrown; } only the body{ }can be effect.and others like .sidebar{ } and .body-head{ } do no effect.