Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Raspberry Pi LCD RealTime data
I've Django 2.0 on my Raspberry Pi 3. I connected 2x16LCD to this device. I'm looking for ways to display sensor data and time on screen in real time. Here's my views.py: from django.shortcuts import render from engine.functions import lcdF def index(request): if 'temp' in request.POST: lcdF.printTemp(0,2) elif 'time' in request.POST: lcdF.printTime() return render(request, 'system/index.html') In the index.html file I've two buttons who sends POST request And here is lcdF.py: import time from datetime import datetime from engine.lib import lcd, temp config = lcd.LCD() def printWelcome(): config.lcd_clear() config.lcd_display_string("System", 1) config.lcd_display_string("aktywny", 2) def printLong(self, string, row): config.lcd_clear() my_long_string = string my_long_string = my_long_string + " " config.lcd_display_string(my_long_string[:19], row) for i in range(0, len(my_long_string)): lcd_text = my_long_string[i:(i + 20)] config.lcd_display_string(lcd_text, row) time.sleep(0.3) # self.display.lcd_clear() def printTime(): config.lcd_clear() config.lcd_display_string("ZEGAR:", 1) while True: data = datetime.now().strftime('%d.%m.%y %H:%M') config.lcd_display_string(data, 2) time.sleep(1) def printTemp(number, frequency): config.lcd_clear() config.lcd_display_string("TEMP:", 1) while True: x = round(temp.read_temp(), number) temperature = "{temp:." + str(number) + "f}" string = str(temperature.format(temp=x)) config.lcd_display_string(string + " C", 2) time.sleep(frequency) It's work inccorect, these two functions interfere with each other Is it a good idea to get data value through the while True loop? -
User Ability to Search Django Database
I am looking to create a very simple form with several drop down fields allowing users to query a database of restaurants I have created (I would like to use the fields 'food', 'city' and 'average rating'). Whilst I have found an approach to do this using separate html pages (Django form to query database (models)) I would like to implement this on one page (restaurants.html). I am using Python 3.1.0, Django 2.0.1 and Bootstrap 4.0. Appreciate all your help. My models.pyis as follows: from django.db import models import numpy as np # Create your models here. class Restaurant(models.Model): name = models.CharField(max_length=100, null=False) desc = models.CharField(max_length=100) web = models.CharField(max_length=100) phone = models.CharField(max_length=40) address = models.CharField(max_length=100) post_code = models.CharField(max_length=20) picture = models.ImageField(upload_to='images/restaurants', null=True) map = models.ImageField(upload_to='images/restaurants', null=True) FOOD = ((1,'English'), (2,'French'), (3,'American'), (4,'Indian'), (5, 'Undefined')) food = models.IntegerField(choices=FOOD, default=5) CITY = ((1,'London'), (2,'Paris')) city = models.IntegerField(choices=CITY, default=1) STARS = ((1,'One'), (2,'Two'), (3,'Three'), (4,'Four'),) CB_rating = models.IntegerField(choices=STARS, default=4) def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def __str__(self): return self.name views.py: from django.shortcuts import get_object_or_404, render from .models import Review, Restaurant from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from .forms import ReviewForm import datetime def review_list(request): latest_review_list = Review.objects.order_by('-pub_date')[:9] … -
Disable button after one week
I made a page where you can place a comment. You can also delete your comment with a delete button. What I want is that after you placed a comment you have one week to delete it. So after a week I want to hide the delete button. When trying to do this I'm getting this error: '<' not supported between instances of 'datetime.timedelta' and 'int' view: class TechnologyDetailView(DetailView): model = Technology def get_queryset(self): group_permissions = Permission.objects.filter(group__user=self.request.user) query = Technology.objects.filter(pk=self.kwargs['pk'], is_active=True, permission__in=group_permissions) for tech in query: comments = Comment.objects.filter(technology=tech) now = datetime.now() for comment in comments: comment.timestamp = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') print(comment.timestamp) age = now - comment.timestamp if age < 604800: comment.is_removable = True else: comment.is_removable = False return query template: <h3>Comments</h3> {% for comment in technology.comment_set.all %} <div class="row" style="border-bottom-style:solid; border-bottom-width:1px; border-color:gray;"> <h6 style="font-weight:bold">Written by {{ comment.user.name }} on {{ comment.timestamp }}</h6> <span>{{ comment.content|breaks }}</span> <p>{{ comment.timestamp | timesince }}</p> {% if comment.user == request.user %} <a class="modal-trigger right" href="#modal_{{ comment.pk }}">Delete Comment</a> {% endif %} <div id="modal_{{ comment.pk }}" class="modal"> <div class="modal-content"> <iframe frameborder="0" id="encoder_iframe" height=300px width="100%" src="{% url 'delete- comment' comment.pk %}"></iframe> </div> </div> </div> {% empty %} <p>There are no comments</p> … -
Django HTTP request to api
So i been trying to get this to work but at the same time i do not understand some of these code means. I'm sorry for making the question so long but i want to understand how these works. I am trying to make a HTTP request to another API to do POST and GET method using django. Based on the website code example, which is this url: https://www.twilio.com/blog/2014/11/build-your-own-pokedex-with-django-mms-and-pokeapi.html As i wanted to use HTTP Request on my API to call other API, therefore i wanted to get a better understanding of how these works and how to use it. The code is at the bottom of the website. But i will just provide the code here so it is easier for you. website code from django_twilio.views import twilio_view from twilio.twiml import Response import requests import json BASE_URL = 'http://pokeapi.co' def query_pokeapi(resource_uri): url = '{0}{1}'.format(BASE_URL, resource_uri) response = requests.get(url) if response.status_code == 200: return json.loads(response.text) return None @twilio_view def incoming_message(request): twiml = Response() body = request.POST.get('Body', '') body = body.lower() pokemon_url = '/api/v1/pokemon/{0}/'.format(body) pokemon = query_pokeapi(pokemon_url) if pokemon: sprite_uri = pokemon['sprites'][0]['resource_uri'] description_uri = pokemon['descriptions'][0]['resource_uri'] sprite = query_pokeapi(sprite_uri) description = query_pokeapi(description_uri) message = '{0}, {1}'.format(pokemon['name'], description['description']) image = '{0}{1}'.format(BASE_URL, sprite['image']) frm … -
Template in Django doesn't show same content for 2 paths
For this template, everything will show fine, but only for the first course. If I add lectures for another course, template won't show them. def courses(request, slug): con = get_object_or_404(Course, slug=slug) context = { 'course': con, 'lectures': con.lectures.all(), 'categories': con.categories.all(), } return render(request, 'courses/courses.html', context) <ul> {% for a in categories %} <li><strong>{{ a.course_category }}</strong></li> {% for c in lectures %} {% if a == c.course_category %} <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% if c.link %} <li>{{ c.link }}</li> {% endif %} {% if c.file %} <li><a href='{{ MEDIA_URL }}{{ c.file.url }}'>download</a></li> {% endif %} {% endif %} {% endfor %} {% endfor %} </ul> -
Django templates, views merge lines in table
I have a view that aggregates columns using annotate and I am aggregating 5 columns, one of which is Sum and the others are Count. The data is received from SQL. So it looks like this: data = super().get_queryset() val = data.values('col1', 'col2', 'col3', 'col4', 'col5) final_data = val.annotate(col1=Sum('col1), col2 = Count(Case(When(type='A' then=1), output_filed(IntegerField())), col3 = Count(Case(When(type='B' then=1), output_filed(IntegerField())), col4 = Count(Case(When(type='C' then=1), output_filed(IntegerField())), col5 = Count(Case(When(type='D' then=1), output_filed(IntegerField()))) This is working to show the results, however I need to show it all in one line. This is how it displays now: List Col1 Col2 Col3 Col4 Col5 A 7895 12 0 0 0 A 0 0 12 0 0 A 2198 0 0 4 0 But I need it to show like this: List Col1 Col2 Col3 Col4 Col5 A 10093 12 12 4 0 What approach is best to achieve this, and how? -
Segmentation fault (core dumped) in django alongside server also sidconnected
i'm trying to plot line chart using Matplotlib and mpld3 with Django . its working properly but if i hit refresh button in browser to reload the page suddenly server getting stopped with error message [Segmentation fault (core dumped)] . bellow i mentioned my code . thanks in advance !! in views.py : from django.shortcuts import render from django.http import HttpResponse import matplotlib.pyplot as plt , mpld3 def index(request): fig = plt.figure() plt.plot([1,2,3,4,5],[5,4,3,2,1],'r--') g = mpld3.fig_to_html(fig) return render(request,'index.html',{'a' : g}) -
Django: ModelFormMixin not rendering form
I've got the following problem. I have a webapp where a genericListView of 'Speakers' allows the user to click on profiles - which then causes to load a detailview which displays the Speakers profile. So far so good, however, from there I want to enable the user to contact / hire the expert. This is done through a form at the bottom of the DetailView, which generates a new 'Quotation' object. So I want to display a submission/create form for the 'Quotation' object inside a genericDetailView for the 'Speaker' object. I thought I could solve this with the 'ModelFormMixin', but even though the DetailView inherets from this mixin and the 'formclass' has been set, no form appears in the template. This is the detailview class SpeakerDetail(ModelFormMixin, DetailView): template_name = 'v2templates/speakers/speaker_detail.html' model = Speaker menu_id = "speaker" form_class = QuotationForm def get(self, request, *args, **kwargs): qs = (self.model.objects.filter(status=STATE_ACTIVE) .distinct().prefetch_related(oabs, 'sociallink_set')) pk = self.kwargs.get('pk') slug = self.kwargs.get('slug', None) self.object, slug_matched = get_slug_object_or_404(qs, pk, slug) if not slug_matched and self.object and self.object.slug: return redirect(self.object) if not self.object: raise Http404 context = self.get_context_data(object=self.object) return self.render_to_response(context) And this is the ModelForm I am linking to: class QuotationForm(ModelForm): class Meta: model = Quotation fields = [ … -
Connect Django backend with Chatfuel bot
I have this problem where I have to connect a Django project with a Chatfuel bot. In my application I have certain activities that are assigned to the users registered in the panel, when these activities are updated, are about to end or you just want to know what it objective is, I have to send a message to the user through Facebook letting him know this information. The first problem I have is that I do not know how to connect the profile of my user in Django with his Facebook profile, that is, how the bot will know which activities are the ones that correspond to him based on his profile in Django. Later the second problem I have is that since they are linked, how can I send the messages through Facebook. Any ideas? -
Using Python 3 in virtualenv not working properly
python 3.5.2 run cmd ( virtualenv -p python3 venv) Already using interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /var/www/html/python3_virtualenv/bin/python3 Also creating executable in /var/www/html/python3_virtualenv/bin/python Installing setuptools, pip, wheel... stay of execution -
How to display ckeditor in template django?
I have installed ckeditor for django and it is displayed in the admin as it should, but how do I make it display in my template. template {% extends 'blog/base.html' %} {% load crispy_forms_tags %}{%block content%} {% if user.is_superuser %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form class="form-horizontal" id="label-edit" role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> {% else %} <h1 class="display-4 text-center">404 Not Found</h1> {% endif %} {% endblock %} I am using crispy forms. I want the ckeditor to appear on the template. Thanks in advance. -
django.db.utils.DatabaseError: Cannot add foreign key constraint in MultiDB
I am trying to migrate my app name notifications in to different db (name is notificationcenter) but getting error in Foreign key constraint, I know the limitations of Django in multiple database but both models (i.e notification_template, gateway_status) will migrate in same database, Please go through given details. I've also added this router in to settings.py dbrouter.py: class NotificationRouter(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'notifications': return 'notificationcenter' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'notifications': return 'notificationcenter' return None # def allow_relation(self, obj1, obj2, **hints): # """ # Allow relations if a model in the auth app is involved. # """ # if obj1._meta.app_label == 'auth' or \ # obj2._meta.app_label == 'auth': # return True # return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if app_label == 'notifications': return db == 'notificationcenter' else: return False # elif db == 'default': # # Ensure that all other apps don't … -
Browsable API becomes unreadable when too many child relations
How can I limit the number of child relations listed in the HyperlinkedModelSerializer's HyperlinkedRelatedField? When there's hundreads or thousands of child relations, the whole page becomes very quickly unreadable and slow. The page-size itself is not the problem, but how many child relations are visible. class FooSerializer(serializers.HyperlinkedModelSerializer): bars = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='bar-detail') class Meta: model = Foo fields = '__all__' class Bar(models.Model): name = models.CharField(max_length=200) foo = models.ForeignKey(Foo, related_name="bars", on_delete=models.PROTECT) In the browsable API: /api/v1/foos/ { "count": 6, "next": null, "previous": null, "results": [ { "url": "http://localhost:8000/api/v1/foos/1/", "name": "Something" "bars": [ "http://localhost:8000/api/v1/bars/3/", "http://localhost:8000/api/v1/bars/4/", "http://localhost:8000/api/v1/bars/5/", "http://localhost:8000/api/v1/bars/6/", "http://localhost:8000/api/v1/bars/7/", "http://localhost:8000/api/v1/bars/8/", "http://localhost:8000/api/v1/bars/9/", "http://localhost:8000/api/v1/bars/10/", "http://localhost:8000/api/v1/bars/11/", "http://localhost:8000/api/v1/bars/12/", "http://localhost:8000/api/v1/bars/13/", ..... As you can see this list becomes very long very quickly. Would be good to cut it to max five or so. For the Form input-fields there HTML_SELECT_CUTOFF but I believe there's nothing similar to read_only=True fields? -
django make a list of objects from queryset
i have a field in models with name answer ,This field has 4 values either a,b,c and d . I am writing a view to create a list of this answer.. I have user the code platform = get_object_or_404(Platform, user=request.user, test_key=article) b = json.loads(platform.list) ans = list(Upload.objects.filter(id__in=b).values_list('answer',flat=True)) and this gives me ans as [(u'a',), (u'b',), (u'c',), (u'b',), (u'c',), (u'b',), (u'c',)] but i want the list as [a,b,c,b,c] I am stuck with this -
How to implicitly pass user from a request to corresponding serializer?
I have a following code: class Article(models.Model): ... owner = models.ForeignKey(User, on_delete=models.CASCADE) class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content', 'owner') extra_kwargs = { 'owner': {'write_only': True}, } class ArticleList(generics.ListCreateAPIView): serializer_class = ArticleSerializer def get_queryset(self): user = self.request.user return Article.objects.filter(owner=user.id) def post(self, request, *args, **kwargs): request.data['owner'] = self.request.user.id return self.create(request, *args, **kwargs) I have to explicitly pass user from request in post method of ArticleList ApiView to satisfy ForeignKey non-empty requirement. This is fine. But I have another models with a ForeignKey to User and as a result it leads to many copy-paste lines, especially in POST and PUT methods. Does anybody knows more elegant DRY solution? -
How to get to Django server logs if server is started in Docker
Folks, I created a Django project and I started it in Docker. Therefore I don't see server logs and I need to know how POST and GET methods look like. How I can get acces to this logs? BR, Damian -
Cross-Origin Request Blocked issue using Aagular 4 and DJango
I have two applications on two machine. Backend app using DJango (example 123.431.234.123:8080) Frontend app using angular (example 123.431.234.124:4200) Now I am trying to post request from angular this.http.post<any>('http://123.431.234.123:8080/login/', { username: username, password: password }) I am getting error on browser: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://123.431.234.123:8080/login/. (Reason: CORS header âAccess-Control-Allow-Originâ missing). When I am trying with curl command on my ubuntu machine, I am able to get the response successfully. curl -d '{"username":"admin" ,"password":"carpediem"}' -H "Content-Type: application/json" http://123.431.234.123:8080/login/ I tried to follow many links and also setup my django setting.py file as link 1 link 2 and did step by step configuration as below pip install django-cors-headers Adds to installed apps INSTALLED_APPS = ( ... 'corsheaders', ... ) Add MIDDLEWARE MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL=True After all changes, I am still facing the same issue. It might be duplicate question, But Please help me to solve it. I am using Mozila firefox, Do I need to do any changes in browser or any other seetings? -
How the hell to add a field on django 1.7 admin panel?
I see a list of fields in the model, but if I add one it won't appear in the admin form, where I need to add a variable to let it appear in the admin html form? code: class Test(models.Model): name = models.CharField('name', max_length=100) f1 = models.CharField('f1', max_length=100, blank=True) f2 = models.CharField('f2', max_length=100, blank=True, null=True, default=None) f3 = models.TextField("f3", blank=True, null=True, default=None) f4 = models.ManyToManyField(Genre, blank=True) f5 = models.ImageField('f5', upload_to=poster_directory_path, blank=True, null=True, default=None) f6 = models.PositiveIntegerField("f6", blank=True, null=True, default=None) f7 = models.DateField('f7', blank=True, null=True, default=None, max_length=50) f8 = models.PositiveIntegerField("f8", blank=True, null=True, default=None, unique=True) f9 = models.FloatField('f9', blank=True, null=True, default=None) f10 = models.FloatField('f10', blank=True, null=True, default=None) -
Is there a way to set DateField nullable=True in SQLAlchemy?
I want to pass empty date into the database (psycopg2.DataError) invalid input syntax for type date: "" My serializer allows it, the database doesn't allow because constraints are not configured. reg_date= Column(Date, nullable=True) -
I cannot access user_detail url
I cannot access user_detail url.I wrote urls.py like from django.conf.urls import url from . import views app_name = 'users' urlpatterns = [ url(r'^(?P<user_id>[0-9a-zA-Z]{20})/user_detail$', views.UserDataSet.get_user_detail, name='user_detail'), url(r'^', views.UserDataSet.get_users, name='get_users'), ] I can access get_users's url by http://localhost:8000/users , but when I access http://localhost:8000/users/sdc452ne3n9mtt6j5k8a/user_detail,I cannot access the page.sdc452ne3n9mtt6j5k8a's user id is ok.I tried to the url like http://localhost:8000?users/sdc452ne3n9mtt6j5k8a/user_detail,I cannot access the page too.I really cannot understand why I can't access the page.What is wrong?How can I access it? -
Django one to one field RelatedObjectDoesNotExist
I made these models: class Post(models.Model): title = models.CharField(max_length=50, blank=True, null=True) class OrderInfo(models.Model): post = models.OneToOneField(Post, on_delete=models.CASCADE, primary_key=True) position = models.CharField(max_length=50, blank=True, null=True) @receiver(post_save, sender=Post) def update_order_info(sender, instance, created, **kwargs): if created: OrderInfo.objects.create(post=instance) instance.orderinfo.save() In View, ... post.orderinfo.position = form.cleaned_data.get('position') ... and It returns RelatedObjectDoesNotExist Error. Post has no orderinfo. What shoud I do? (I think Django System is handling .orderinfo as a post's column.. But Why?) -
DRF: How to make field in serializer required only for object creation?
I'm using Django Rest Framework and have a following serializer (minimal example): class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('id', 'brand', 'color') extra_kwargs = { 'brand': {'required': True}, } So using POST it works as expected and prevents car creation without a brand in request params. But then I want to update some Car entity in DB and modify only a color field. Using PUT (or PATCH) like this: http PUT :8000/cars/123/ color="red" There are some errors: { "brand": [ "This field is required." ] } How can I make the brand field required only for object creation but not for modifying? -
How do I push my Bitbucket repo to my DigitalOcean server?
I've created a DigitalOcean server (droplet) for my Django site, running Ubuntu 16.04 with Nginx & Gunicorn. I've got my Django project in a Bitbucket repo - how do I push this to my DigitalOcean server? I've tried to search and there are many different/confusing answers and they all seem more complicated that it should be. Help appreciated. -
Django Integrity Error Not null
i am learning django and trying to practice by making my own website that will quiz me with questions that i submit in to it. I get this error and i dont know why. IntegrityError at /questions/new/ NOT NULL constraint failed: questions_question.date_created This is the relevent traceback i believe enter image description here here is my relevant code: questions/Views.py from django.shortcuts import render from django.views import generic from django.core.urlresolvers import reverse_lazy from django.contrib import messages from . import models from . import forms # Create your views here. class QuestionList(generic.ListView): model = models.Question class QuestionDetail(generic.DetailView): model = models.Question def get_queryset(self): queryset = super().get_queryset() class CreateQuestion(generic.CreateView): model = models.Question # form = QuestionForm fields = ('question', 'answer') def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeleteQuestion(generic.DeleteView): model = models.Question success_url = reverse_lazy('questions:all') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, "Question Deleted") return super().delete(*args, **kwargs) Here is my models.py from django.db import models from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse User = get_user_model() import misaka # Create your models here. class Quiz(models.Model): name = models.CharField(max_length=225) intro_text = models.TextField(null=True) date_created = models.DateTimeField() date_updated = models.DateTimeField(auto_now=True, null=True) class Question(models.Model): user = models.ForeignKey(User, related_name="question", … -
Why the `/admin/` only have few models?
I use the admin account login to the /admin/: Why there are only these field I can edit? I have write tons models in my project. why do not show up?