Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Persistent in-memory objects in Django
I'm trying to build a chatbot using Django and for this I need to keep some object in memory that preserves the state. I'm using Django and Django-channels for build this application, however, for every request it creates a new object from a database and I can't find any way to preserve the state. Any advice? Thanks in advance! -
Connect plaid.io with django
I'm just trying to connect plaid.io with Django. To do that, I'm using the examples. https://github.com/plaid/quickstart/tree/master/python server.py import os import datetime import plaid from flask import Flask from flask import render_template from flask import request from flask import jsonify app = Flask(__name__) # Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys PLAID_CLIENT_ID = 'xxxxxxxxxxxxxx' PLAID_SECRET = 'xxxxxxxxxxxxxx' PLAID_PUBLIC_KEY = 'xxxxxxxxxxxxxx' # Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good, # password: pass_good) # Use `development` to test with live users and credentials and `production` # to go live PLAID_ENV='sandbox' client = plaid.Client(client_id = PLAID_CLIENT_ID, secret=PLAID_SECRET, public_key=PLAID_PUBLIC_KEY, environment=PLAID_ENV) @app.route("/") def index(): return render_template('index.ejs', plaid_public_key=PLAID_PUBLIC_KEY, plaid_environment=PLAID_ENV) access_token = None public_token = None @app.route("/get_access_token", methods=['POST']) def get_access_token(): global access_token public_token = request.form['public_token'] exchange_response = client.Item.public_token.exchange(public_token) # print 'access token: ' + exchange_response['access_token'] access_token = exchange_response['access_token'] return jsonify(exchange_response) @app.route("/set_access_token", methods=['POST']) def set_access_token(): global access_token access_token = request.form['access_token'] # print 'access token: ' + access_token return jsonify({'error': False}) @app.route("/accounts", methods=['GET']) def accounts(): global access_token accounts = client.Auth.get(access_token) return jsonify(accounts) @app.route("/item", methods=['GET', 'POST']) def item(): global access_token item_response = client.Item.get(access_token) institution_response = client.Institutions.get_by_id(item_response['item']['institution_id']) return jsonify({'item': item_response['item'], 'institution': institution_response['institution']}) @app.route("/transactions", methods=['GET', 'POST']) def transactions(): global access_token # Pull transactions for the last 30 days start_date … -
IntegrityError: (1048, "Column 'field' cannot be null") even though null=True
I'm getting an Integrity error in Django and I'm struggling to understand why. When I try to save my formset I get the error IntegrityError: (1048, "Column 'add_row' cannot be null" But in my models I've allowed the field to be null, so I don't understand why this error is being raised? class Time(models.Model): description = models.CharField(max_length=150, null=True, blank=True) timesheet_id = models.ForeignKey(TimeSheet, null=True, related_name="time_set") field = models.CharField(max_length=10, null=True, blank=True, editable=False) def __unicode__ (self): return self.description or u'' Here's my traceback: Internal Server Error: /app/2/timesheet/week/submit/ Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/username/Documents/code/project/app/views.py", line 394, in my_view time_formset.save() File "/Library/Python/2.7/site-packages/django/forms/models.py", line 645, in save return self.save_existing_objects(commit) + self.save_new_objects(commit) File "/Library/Python/2.7/site-packages/django/forms/models.py", line 775, in save_new_objects self.new_objects.append(self.save_new(form, commit=commit)) File "/Library/Python/2.7/site-packages/django/forms/models.py", line 913, in save_new obj.save() File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 700, in save force_update=force_update, update_fields=update_fields) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 728, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 812, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 851, in _do_insert using=using, raw=raw) File "/Library/Python/2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 1039, in … -
Object needs to have a value for field "id" before this many-to-many relationship can be used in Django
I have the following code in my models.py: class Tag(models.Model): name = models.CharField(max_length=75) class Article(models.Model): tags = models.ManyToManyField(Tag) def save(self, *args, **kwargs): for tag in self.tags: print tag.name super(Article, self).save(*args, **kwargs) When I try to create an article from the admin panel, I get the following error: ValueError: "<Article>" needs to have a value for field "id" before this many-to-many relationship can be used. How can I fix this problem? I need to access and iterate the tags before saving the article. Thanks! -
ERR wrong number of arguments using celery
This is my first time using django celery.When I go on http://localhost:6379/ I am getting an error that says: -ERR wrong number of arguments for 'get' command I would like to get some help to get to fix this error. Thank you -
django-fluent-comments model doesn't appear in Wagtail ModelAdmin
I have a Wagtail project that uses django-fluent-comments and I would like to be able moderate the comments in the admin pages. Based on this tutorial I added this to my wagtail_hooks.py file: class CommentAdmin(ModelAdmin): model = FluentComment menu_label = 'Comments' menu_icon = 'list-ul' menu_order = 200 add_to_settings_menu = False list_display = ('user', 'comment') modeladmin_register(CommentAdmin) But when I go to the Admin pages, there is no comments tab and no errors shown. I have tried to add a Pages model to my Admin page and that worked fine. The FluentComment model is just: class FluentComment(Comment): """ Proxy model to make sure that a ``select_related()`` is performed on the ``user`` field. """ objects = FluentCommentManager() class Meta: proxy = True (In this file) So I wonder if I have the correct model. But the if I add print model.objects.all() to my CommentAdmin class it shows all my comments in the log. -
Getting a wierd ValueError in creating entry in django model
I am creating an entry in Django model but it is showing ValueError for a field that doesn't even Exist I am using external script inside manage.py shell with python3 manage.py shell >>> exec(open('file_name.py').read()) file_name.py (ignore the name :D) from jtc.models import * m = Movies.objects.get(title__icontains = "Badrinath") mul = Multiplex.objects.get(movie__icontains = 'Badrinath', name = "PVR") date = mul.date.all() time = mul.time.all() seat = Snumber.objects.filter(seat_avail = True) st = Snumber.objects.get(seat_avail = True, seat_name = 'A1') dt = Date.objects.get(date = '2017-05-10') tm = Time.objects.get(timing='09:00:00') Seats.objects.bulk_create( [ Seats(movie_name = m, multiplex_name = mul, seat_no = st, date = dt, time=tm, seats = 1 ), ] ) This is error which i am getting Traceback (most recent call last): File "<console>", line 1, in <module> File "<string>", line 23, in <module> File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 550, in __init__ setattr(self, prop, kwargs[prop]) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__ manager = self.__get__(instance) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__ return self.related_manager_cls(instance) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__ (instance, self.source_field_name)) ValueError: "<Seats: PVR Dehradun Badrinath ki dulhaniya 2017-05-10 09:00:00>" needs to have a value for field "seats" before this many-to-many relationship can be used. -
How to test view which calls api
How can I unit test a view, which calls an external api? Because I don't have influence on what the api returns. def shorten(request, question_id, results): if not Question.objects.filter(pk=question_id).exists(): raise Http404('Can not shorten url of non-existing question') url = request.build_absolute_uri(reverse('polls:results' if results else 'polls:vote', args=(question_id,))) try: payload = {'longUrl': url, 'access_token': SHORTEN_SERVICE_ACCESS_TOKEN, 'format': 'txt'} response = requests.get('https://api-ssl.bitly.com/v3/shorten', params=payload) response.raise_for_status() except HTTPError as http_error: logger.error('Shorten service failed with status code {} ({})'.format(http_error.response.status_code, http_error.response.text)) return HttpResponseServerError(status=503) except RequestException as request_exception: logger.error('Connection to shorten service failed ({})'.format(request_exception)) return HttpResponseServerError(status=500) else: shortened = response.text return HttpResponse(shortened, content_type="text/plain") -
Django - Set different id for each radio button choice
I want to set different id for each radio choice. My Model:- class Preference(models.Model): BOARD_CHOICES = [('CB', 'CBSE'), ('IC', 'ICSE'), ('SB', 'State Board'), ('IB', 'International Board')] Board = models.CharField(max_length=30, choices=BOARD_CHOICES, default='CBSE', blank=False) My Form:- class PreferenceForm(forms.ModelForm): class Meta: model = Preference fields = ['Board'] widgets = { 'Board': forms.RadioSelect(), } i.e for the radio button with label 'CBSE' I want to set id to say 'choice_1' and so on. All help/suggestion would be appreciated. -
django-leaflet: How to initialize django-leaflet scripts for open street map inside StackedInline objects?
I have two models with foreignkey relationship. One of them displays like StackedInline object and has a django-leaflet map inside. Inlines added through extra parameter displays correctly. But new one, added with 'Add another' button have empty input instead of a map. -
Django Translation on Heroku is not fully working
I deployed my Django app on Heroku and I added https://github.com/piotras/heroku-buildpack-gettext.git this ugettext buildpack and some parts of the application are note translated. Locally it's working, I don't know where is the issue coming from. For example, the menu item Classes Types is not translated but other parts are. {% trans "Class Types" %} template {% load i18n %} .... <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans "Class Types" %}<span class="caret"></span></a> <ul class="dropdown-menu"> <li> <a href="{% url 'class_type-list' %}"> <span class="glyphicon glyphicon-list" aria-hidden="true"></span> {% trans "All" %}</a> </li> <li> <a href="{% url 'class_type-new' %}"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> {% trans "New" %}</a> </li> </ul> </li> .... ar/LC_MESSAGES.po #: templates/back_office/class_type_list.html:4 #: templates/back_office/menu.html:37 msgid "Class Types" msgstr "انواع الحلقات" en/LC_MESSAGES.po #: templates/back_office/class_type_list.html:4 #: templates/back_office/menu.html:37 msgid "Class Types" msgstr "Class Types" -
Could not parse the remainder: '[plant__id]' from 'total_ecof[plant__id]'
My views.py: def home(request): if not request.user.is_authenticated(): template = 'data/login.html' return render(request, template) else: plants = Plant.objects.filter(user=request.user) total_ecof = [] total_ectr = [] for plant in plants: x = 0 y = 0 for recording in Recording.objects.filter(plant__id=plant.id): x += (recording.time_to_detect * recording.performance_loss) / ( plant.nominal_power * recording.years_of_operation) y += ((10 + 15 + 200 + 50) * plant.no_modules + 240 * 50 * recording.occurrence * plant.no_modules) / ( plant.nominal_power * 3) total_ecof.append(x) total_ectr.append(y) template = 'data/home.html' context = { 'plants':plants, 'total_ecof':total_ecof, 'total_ectr':total_ectr, } return render(request, template, context) my html template {% for plant in plants %} <tr> <td>{{ plant.management_company }}</td> <td>{{ plant.plant_name }}</td> <td>{{total_ecof[plnat.id]}}</td> </tr> {% endfor %} But I get the error: Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '[plant.id]' from 'total_ecof[plant.id]' and I do not understand why. What am I doing wrong? Furthermore, could you please help me to create a bar chart where x axis would be the plants and y axis the corresponding total_ecof. -
rqworker from django-rq not receiving tasks
I am trying to have some asynchronous functions run by a worker following the approach explained here. That means, in my tasks.py file I have: from django_rq import job @job def long_function(one_list): #many stuff that should be done asynchrounously Then in my views.py file: from .tasks import long_function def render_function(request): #some code to get one_list long_function.delay(one_list) #some more code to render the page return render(request, 'results_page.html', context) For the moment I am doing the tests locally. Therefore, I have two Terminals opened: one to run python manage.py runserver and another to run python manage.py rqworker default. So when I load 'results_page.html' in the browser I expect that the tasks are queued and start running with the rqworker. The problem is that this happens only some random times, while in the rest the Terminal for rqworker just shows: *** Listening on default... Sent heartbeat to prevent worker timeout. Next one should arrive within 420 seconds. Sent heartbeat to prevent worker timeout. Next one should arrive within 420 seconds. My first idea was that as I am using two different terminals simultaneously, the connection was not properly done. However, I think this does not make sense because sometimes the asynchronous task does … -
Django authentication security check against LDAP
While studying the Authentication Views in Django I came across some of the build in views including password reset view. I got hang of its basic working mechanism while reading the documentation I encountered the line promoting the use of set_unusable_password() in Djagno authentication against LDAP networks. I googled and found some of the useful links defining LDAP networks e.g. but I was not able to understand the possible vulnerabilities to the LDAP authentication system that may arise when the set_unusable_password flag is not set and the system is requested a password change request. Basically what I am trying to ask is what kind of misuse can occur in case of LDAP authentication and set_unusable_function not being used as said in the following context of the password reset view in Django. Can anyone please kindly highlight some of the misuses I will be really grateful. The Link to the topic is here. Thanks in Advance. -
How to raise django validation error on login form (which is on a bootstrap modal on index.html)?
#below if login view def login_view(request): print(request.user.is_authenticated()) next = request.GET.get('next') title = "Login" form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if next: return redirect(next) return redirect("/userdashboard") return render(request, "index.html", {"form":form, "title": title}) how can i return error message on login form (which is in bootstrap modal) -
Django - use datetime.today is not working
I am working a project on Django. I need to get date of today and push it to database. Here is what i am trying; def addDate(request): all_tables = Table.objects.all() a = Product.objects.get(pk=3) #obj = Date_Product.objects.create(date=datetime.today(), product=a) #obj.save() val = Date_Product.objects.create( date=datetime.date().today, product=a, ) val.save() context = { # informations which templates needs 'all_tables': all_tables, } return render(request, 'main/index.html', context) I have also tried datetime.today() and datetime.date().today(). Also i have imported date and datetime already. -
/django.db.utils.IntegrityError: NOT NULL constraint failed/ after python manage.py migrate app zero
I had some mess with migrations in production and localy. Finally the situation was that in production there were only initial migration and localy there were 8 migrations or something. So I decided to use python manage.py migrate app zero both in production and localy(django 1.8.7). In prodcution it worked but locally it raised error which didn't appear before after makemigrations or migrate command. django.db.utils.IntegrityError: NOT NULL constraint failed: app_userprofile__new.phone_number after few attempts to try different things, the error began to appear after migrate commands too. The model itself : class UserProfile(models.Model): user = models.OneToOneField(User) phone_number = models.IntegerField(null=True, blank=True, default=None) -
Django: empty date string should return all
So, I have a date from input field, and date to input field. When I pass in the date range from and to it works fine. But when I try to leave one or both blank, to get all the items, or partial items, it gives ValueError: Cannot use None as a query value or format error when I try to make the default empty string. def report(self, request): date_from = query['date_from'] if query['date_from'] else None date_to = query['date_to'] if query['date_to'] else None queryset = Client.objects.filter( client_code__in=clients, account__note__creation_time__gte=date_from, account__note__creation_time__lte=date_to, ) To give a better context, if I leave both field empty i should get all items from beginning to now, if I fill in date from field but leave date to field empty, I should get all item from date from till now. If I have date to field buy empty date from field, I should get items from beginning till date to. -
Django View check second model for value
I'm somewhat new to Django so please bear with me here. I have a three models in my app, Company, Articles, and Transcripts. Both Articles and Transcripts have a foreignkey() field that links to the Company model. In my main view I list all of the companies, but I would like to indicate if there is an article or transcript for each of those companies. Here are the models: class Company(models.Model): stock_symbol = models.CharField(max_length=5, unique=False) company_name = models.CharField(max_length=200) address = models.CharField(max_length=300, blank=True) website = models.URLField(max_length=200, blank=True) following = models.BooleanField() class Articles(models.Model): company = models.ForeignKey('Company', related_name='articles') headline = models.CharField(max_length=200) url = models.URLField(max_length=300, blank=True) class Transcripts(models.Model): company = models.ForeignKey('Company', related_name='transcripts') headline = models.CharField(max_length=200) url = models.URLField(max_length=300, blank=True) Below is a view for a single company, however since I'm returning all companies I obviously can't use a primarykey. How would I go about getting this info for each of the companies? Am I setting up my models the right way to do this? class CompanyDetails(generic.DetailView): model = Company template_name = 'company_details.html' def get_context_data(self, **kwargs): pk = self.kwargs.get('pk') context = super(CompanyDetails, self).get_context_data(**kwargs) context['company'] = Company.objects.filter(id=pk) context['articles'] = Articles.objects.filter(company_id=pk).order_by('-date') context['transcripts'] = Transcripts.objects.filter(company_id=pk).order_by('-date') return context -
Changing the Userprofile
Hello i have UserSettings and the user as the possibility to use a ProfilePicture. The Problem is the User cannot change any of his profile Settings. since i get the Error Unique Constraint failed or (thats what i get right now) 'int' object has no attribute '_committed' I think the problem is in the view but i dont know how to change it. My model: class UserSettings(models.Model): profileimage = models.ImageField(verbose_name=_(u"Change Your Profilepicture"),upload_to=upload_location, default=1, blank=True, ) Info = models.CharField(verbose_name=_(u"Tell us about yourself"),max_length=500,default="I'm a Human") status = City = models.CharField(verbose_name=_(u"Where are you from"),max_length=500,default='Earth') user = models.OneToOneField(User, default=1) objects = models.Manager() class Meta: ordering =['-user'] def __unicode__(self): return self.user.username My View: @login_required def userprofiletwo(request): user = request.user form = UserSettingsForm(request.POST or None, request.FILES or None) if form.is_valid(): user = request.user form.save() messages.success(request, 'Your personal Settings are Updated') return redirect('userprofiletwo') context = { 'form':form, } return render(request, 'userprofile/userprofiletwo.html', context) I tried to change the OnetoOne field on the model to FeoreignKey or ManytoMany but this made new userprofiles instead of replacing the old information with new information. Thanks in advise. -
GenericTabularInline isn't returning what it should in my Django Admin
I have the following models.py: class Product(Model): ... class ExtraService(Model): ... class Order(Model): ... class OrderItem(Model): order = models.ForeignKey(verbose_name=_('Order Item'), to=Order) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() item_relation = GenericForeignKey('content_type', 'object_id') quantity = models.PositiveIntegerField(verbose_name=_('Quantity'), default=0) And I'm working my admin.py this way: class OrderItemInlineAdmin(GenericTabularInline): model = OrderItem min_num = 0 extra = 0 fields = ('item_relation', 'quantity',) ct_field = 'content_type' ct_fk_field = 'object_id' class OrderAdmin(admin.ModelAdmin): list_display = ('user_form',) inlines = (OrderItemInlineAdmin,) admin.site.register(Order, OrderAdmin) I can't get my admin to show the OrderItem object inline (which can have a key to either a Product or an ExtraService) with my Order object, followed by its quantity field. Instead, it says the item_relation field doesn't exist. How do I bypass this? PS: I've also tried using my own ModelForm but it still doesn't acknowledge the item_relation field. -
django drf login template
I extend the login template of DRF {% extends "rest_framework/login_base.html" %} {% block branding %} <h3 style="margin: 0 0 20px;">My site</h3> {% endblock %} with urls.py: urlpatterns = [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^login', login, template_name, name='login'), url(r'^logout', logout, template_name, name='logout'), ... Everything works well except if the connection fails: DRF redirect to http://127.0.0.1:8000/api-auth/login/ instead of http://127.0.0.1:8000/login/ and my extended template is not used. So I lose my site name for "Django REST framework" title. Regards -
Deploying asgi and wsgi on Heroku
I'm trying to deploy Django Channels on Heroku using asgi alongside my existing wsgi implementation. Can I deploy both asgi and wsgi to heroku with the following setup? My procfile: web: gunicorn chatbot.wsgi --preload --log-file - daphne: daphne chat.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 chatworker: python manage.py runworker --settings=chat.settings -v2 My asgi.py file: import os from channels.asgi import get_channel_layer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chat.settings") channel_layer = get_channel_layer() My wsgi.py file: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chat.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) And my channel layers in settings.py: CHANNEL_LAYERS = { 'default': { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')] }, 'ROUTING': 'chat.routing.channel_routing', } } -
Mimicking Django's ForeignKey field for external objects
I'm in the process of refactoring a codebase where we plan to outsource certain functionality to an external service. We have a couple of models where we can currently leverage the power of foreign keys for easy ORM manipulation: field_name gives you an ORM representation of the related object and field_name_id let you access the ID of the related object. Although we can't use a foreign key anymore, we'd like to keep using these convenience methods. So instead of just replacing all ForeignKey references to instances of a specific external entity with a PositiveIntegerField, I tried something like this (pseudocode): class ExternalObjectReferenceField(PositiveIntegerField): """ Behaves a bit like a ForeignKey, but records of the model are stored outside our system. The external object is represented internally by readonly ExternalObject instances. """ def get_prep_value(self, value): # Extract ID reference from ExternalObject, save that to database. if value is None: return None elif isinstance(value, Number): return value elif isinstance(value, ExternalObject): return value.id raise ValueError('Badly typed field value for {}'.format(self.name)) def to_python(self, value): if value is None: return None elif isinstance(value, Number): try: return fetch_fancy_python_object_from_external_system(value) except ExternalObjectDoesNotExist: raise ValidationError('Reference to external object seems invalid') raise ValidationError('Invalid field value') This is cool and all, but … -
How to assign BooleanField's icons to IntegerField in Django
I have several (>20) fields with similar possible values and a choices set for them im my Model: predicate_choices = ((0, True), (1, False), (2, 'someParam2'), (3, 'someParam3'),) field1 = models.IntegerField(default=0, choices=predicate_choices, verbose_name='field1') field2 = models.IntegerField(default=0, choices=predicate_choices, verbose_name='field2') field3 = models.IntegerField(default=0, choices=predicate_choices, verbose_name='field3') My question is how I can display 0 and 1 values as those nice BooleanField icons? The are displayed as strings 'True' and 'False' at the moment. As far as I found out, I need to set the .boolean property of a field to True, but just didn't manage to do that. These fields are of integer type in the database itself, by the way.