Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bokeh: ploting multiple separate lines
I cant come up with solving the way how to plot multiple separate lines other than this piece: main_time_line = p.line(x=(start, stop), y=(0, 0)) g1 = p.square(source=source, x='examination__date', y=0, size=4, color='black', name='g1') hover_tool.renderers.append(g1) g2 = p.diamond(source=source, x='examination__date', y='level') for i, (idate, ilevel, iname) in enumerate(zip(source.data['examination__date'], source.data['level'], source.data['examination__name'])): vert = 'top' if ilevel < 0 else 'bottom' horizontal = 'right' if ilevel < 0 else 'left' p.line(x=(idate, idate), y=(0, ilevel), color='black', line_width=3) The result of the above is this: The visual effect is exacly what I want, however the fact that vertical lines are ploted using for-loop, creates problems with widgets, namely: checkboxes react only to square and diamond glyphs. I guess its due to the fact that vert lines are ploted without source arg, therefore emiting changes via JS callback doesnt update data for them. I wasn't able to plot them the way they are while using source arg. Any suggestions please ? -
Django/Wagtail: Segmentation fault (core dumped) after "POST /admin/login/ HTTP/1.1" 302 0 "
Every time I log in to the wagtail administration site, this error occurs. I already restarted the computer but the error still persists. Does anyone know what can it be? As for the program, it's just a blog similar to the wagtail turorial, so I did not stick to things like nginx or anything and it's all pretty simple, so I do not know why this is happening.... -
How to send a template variable in loop in html to javascript?
i have a variable of Post class of model in html and i want to add ability of adding comments to any posts. So i have a js function for on click of button to add comment and i want to send that post_id witch user want to add comment for it but because of this tag is in a loop it always send a same post_id!!! What i can do?? html: {% extends "base.html" %} {% block body_block %} <h2>Profile:</h2> <h2>Posts:</h2> {% for temp_user_posts in user_posts %} <div class="profile_page"> <h3><b>{{ temp_user_posts.post }}</b></h3> <p>{{ temp_user_posts.post_time }}</p> </div> <label for="user-comment">comment:</label> <input id="user-comment" type="text" name="{{ temp_user_posts.pk }}"> <button onclick="add_comment_button();">add comment</button> {% endfor %} {% endblock %} js: function add_comment_button() { alert($('#user-comment').attr("name")); $.ajax({ type: "GET", url: '/user_add_comment', data: { "comment_text": $('#user-comment').val(), "post_pk": $('#user-comment').attr("name"), }, dataType: "json", success: function (data) { location.href = data["url"] }, failure: function () { alert('There is a problem!!!'); } }); } view: def user_add_comment(request): post_pk = request.GET.get('post_pk', None) post = PostModel.objects.get(pk=post_pk) comment = CommentPostModel() comment.post = post user_info = UserProfileInfo.objects.filter(user=request.user) user_info2 = object() for temp_user_info in user_info: user_info2 = temp_user_info break comment.profile_user = user_info2 comment.text = request.GET.get('post_text', None) comment.save() data = { "url":"/profile_page", } return JsonResponse(data) -
Django - output a calculation
I'm trying to output in html a calculation which is based on 2 aggregations (sums) Though, it doesn't display (typerror). Can someone help me out? in views.py: (extract) def calcul(request, slug): numerator = CF.objects.filter(type='inflow').aggregate(sum=Sum('amount')) calculation = numerator / Main.objects.filter(slug=slug).aggregate(sum=Sum('total') return render(request, 'home/detail.html', { 'calculation' : calculation}) in my template : {{ calculation }} -
Django ModelForm with FielField - How can I fix/edit/alter the HTML code -> I want to add linebreaks after each element
I use Django 2.1.7 and I have a blog post ModelForm. One of the fields is a FileField and while everything works, the formatting is horrible. It looks like this: ... Currently:some/path/to/file.jpg[]ClearChange:BUTTON ... While I would much rather want it like this: ... Currently:<single_space>some/path/to/file.jpg<linebreak> <No_clear_button> Change:<single_space>BUTTON ... I hope my "textual drawing" makes sense! :-) Is there an easy way to solve this? I'd really like to keep using ModelForms, because it is just so straight-forward. I don't understand why the standard output is so messy. I can hardly believe that anyone would like to use it the way it comes out of the box. Either way: Is there a way I can change this? Thank you so much in advance! -
In my django HTML template my text is repeated because of {% for city in cities %} loop
My text in my HTML is repeated because of the {% for %} loop. I already tried to move {% if %} outside of {% for %}. Then my disappears. This is my html template {% for city in cities %} {% if city.author.access_challenge %} <p class="small text-center"> In order to get information about this contact us through almaz@protonmail.com </p> {% else %} <table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;"> <tbody> <tr> <td><a class="text-uppercase" href="{% url 'users:address' city.pk %}">{{ city.city }}</a></td> </tr> </tbody> </table> {% endif %} {% endfor %} This is my views.py def cities(request, pk): country = Post.objects.get(id=pk).country cities = Post.objects.filter(country=country).distinct('city') context = { 'cities':cities, 'country':country } return render(request, 'users/cities.html', context) Also I tried to change my views.py like this: def cities(request, pk): country = Post.objects.get(id=pk).country ci = Post.objects.filter(country=country).distinct('city') cit = list(ci) for city in cit: for cities in cit: context = { 'cities':cities, 'country':country } return render(request, 'users/cities.html', context) But when I used the for loop, I get an error that Post is not iterable. -
Django ManyToManyField referenced in loop
My problem looks like this - I have many to many field that I need to reference multiple times in the loop. Each time I have to do it with another id. Every solution I can think of seems pretty heavy and I want to do it nice and clean I'm just out of the ideas (the problem is probably my little experience with Django and Python). Right now I have something like this (it obviously doesn't work): projects = Project.objects.order_by('name').values() for project in projects: currentProject = Project.objects.get(pk=project['id']) projects[index] = { 'genres': currentProject.genres.all().values() } context = { 'projects': projects, } I have been looking for the answer for like 2 hours now and couldn't find what I was looking for so I hope someone here can give me some advices. Thanks -
Form function is always passing as valid
I created a form and a view that checks if a user's input, lesson_instrument and lesson_level, match the user object's values of instrument1 and level1. The form is intended to pass if lesson_instrument == instrument1, and level1 >= lesson_level. However, no matter the input I put in the form, the form always passes as valid, it doesn't fail, even when the function does not meet the requirements. I would greatly appreciate any help in solving this issue as I can't seem to figure out what's wrong. forms.py class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_level = forms.ChoiceField(choices=level_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_length = forms.ChoiceField(choices=length_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_day = forms.ChoiceField(choices=day_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_time = forms.ChoiceField(choices=time_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_weekly = forms.BooleanField(required=False) class Meta: model = Lesson fields = ('lesson_instrument', 'lesson_level', 'lesson_length', 'lesson_day', 'lesson_time', 'lesson_weekly') def lesson_allowed(self): # Check that the user is allowed to teach that instrument and level lesson_instrument = self.cleaned_data.get("lesson_instrument") lesson_level = self.cleaned_data.get("lesson_level") if lesson_instrument == user.instrument1: level1 = user.level1 if lesson_level == "Beginner": lesson_level = 1 if level1 == 'Beginner': level1 = 1 if level1 >= lesson_level: return lesson_instrument return lesson_level … -
django uwsgi nginx recv() failed (104: Connection reset by peer) while sending to client
I'm getting this error in some requests to my django application while using nginx with uwsgi. I used post-buffering and buffer-size but my problem continued. please help me if you can :(strong text recv() failed (104: Connection reset by peer) while sending to client -
Django how to show two models in the same form in admin
I am trying to show 2 models in the same admin form in order to add surveys and questions (multiple questions for a survey) in the same form. Inline doesn't seem to work properly for me. Here is my model: class Survey(models.Model): survey_title = models.CharField(max_length = 100) total_votes = models.IntegerField(default = 0) def __str__(self): return self.survey_title class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question_body = models.CharField(max_length = 300) question_select= models.BooleanField def __str__(self): return self.question_body class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer_body = models.CharField(max_length = 200) answer_votes = models.IntegerField(default=0) def __str__(self): return self.answer_body // this doesn't seem to do anything class SurveyAdmin(admin.ModelAdmin): list_display = ('Survey', 'Question', 'Answer') and my admin.py is from django.contrib import admin from .models import Survey, Question, Answer # Register your models here. admin.site.register(Survey) admin.site.register(Question) admin.site.register(Answer) //again this doesn't seem to do anything class QInline(admin.TabularInline): model = Question class SurveyAdmin(admin.ModelAdmin): inlines = [ QInline, ] thanks in advance for your help, -
Django celery periodic tasks run only once in production
I'm using celery 4.2.1 and setting celery periodic tasks using django_celery_beat in admin. Works fine locally, but at the server all periodic tasks run only once. And all tasks will run again (one more time), if I update at least one task in admin by hitting save. in celery.py I have: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Celery settings in settings.py: CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" CELERY_TIMEZONE = TIME_ZONE To start celery : celery -A proj worker -l info To start beat: celery -A proj beat -l info How to fix that problem? Thank you for your time and help. -
how to put present data from one table to another
I have a product model. How do I get the products to be added to transaction model that can save multiple products and its price? I tried using using a foriegn key for product. and stackedinline -
Django==2.1 , setting DEBUG to False results in 500 server error
I have the following settings.py file for my django project: """ Django settings for framework project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os from datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '**************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', 'graphql_jwt.refresh_token.apps.RefreshTokenConfig', 'django_filters', 'sass_processor', 'hamlpy', 'ckeditor', 'easy_select2', 'members', 'activity', 'blog', 'pages', 'status', 'gsoc' ] 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'framework.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'static')], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': ( 'hamlpy.template.loaders.HamlPyFilesystemLoader', 'hamlpy.template.loaders.HamlPyAppDirectoriesLoader', ), }, }, ] WSGI_APPLICATION = 'framework.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Django with M2M Intermediary-Through-Model: list_display and Views
I am writing a Django app to track my Magic card collection. I am quite happy with the models now and the Admin interface works. I can add new cards, collections and copies of cards and everything behaves as expected. However, I would now like to list add attributes from my through model relationship to list_display in the Admin section. Basically, I want to list copies, copies_foil and copies_premium for each collection with the entry for each card. Both in the list_display and later on in Views. How do I do that? Here's my models.py: from django.db import models class Expansion(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Expansion') symbol = models.CharField(max_length=3, unique=True, primary_key=True, verbose_name='Expansion Symbol') released = models.DateField() added = models.DateField(auto_now_add=True) modified = models.DateField(auto_now=True) def __str__(self): return '%s' % (self.symbol) class Card(models.Model): LAND = 'L' COMMON = 'C' UNCOMMON = 'U' RARE = 'R' MYTHIC = 'M' TOKEN = 'T' RARITY_CHOICES = ( (LAND, 'Land'), (COMMON, 'Common'), (UNCOMMON, 'Uncommon'), (RARE, 'Rare'), (MYTHIC, 'Mythic Rare'), (TOKEN, 'Token'), ) WHITE = 'W' BLUE = 'U' BLACK = 'B' RED = 'R' GREEN = 'G' COLOURLESS = 'C' GOLD = 'M' COLOUR_CHOICES = ( (WHITE, 'White'), (BLUE, 'Blue'), (BLACK, 'Black'), (RED, 'Red'), (GREEN, 'Green'), (COLOURLESS, … -
I am trying to create custom user registration form
I am getting this error.Below mentioned code is for forms.py from django import forms from dappx.models import UserProfileInfo from django.contrib.auth.models import User class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['username','password','email'] class UserProfileInfoForm(forms.ModelForm): class Meta: model = UserProfileInfo fields = ['portfolio_site','profile_pic'] -
Where do I put the logic for a webscraper in my app and how do I trigger it when a model object is created - Django
I am practicing Django by creating a web application where I can email in a word, the application then translates it (from eng - spanish or vice versa) and sends me a few words each day to learn. My problem: I don't know where to put the webscraper code that translates search terms and I don't know how to trigger it when a search term is received so that the result can be added to the Results model Models I have two models currently. The first model contains my search terms and the second model contains the translation results - both inherit from an abstract model with common fields: from django.db import models from django.conf import settings class CommonInfo(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Search(CommonInfo): search_term = models.CharField(max_length=100) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True ) def __str__(self): return self.search_term class Result(CommonInfo): search = models.ForeignKey( Search, on_delete=models.SET_NULL, null=True ) translation = models.CharField(max_length=100) example = models.TextField() is_english = models.BooleanField(default=True) def __str__(self): return self.translation My View My view has a single entry point which receives an http POST request containing a parsed email from a Sendgrid parser. It extracts the word to be translated (from the … -
Redirect After Ajax call using Django if query's match
I grasp that this code isn't working because the request is somehow insufficient, but I'm uncertain as to how to go about correcting it. I'm trying to configure it so that, if the ajax data matches the username, it will redirect to home.html. Any help would be so greatly cherished! (PS: the print calls are working - if the user exists, it prints the "else" statement and vice versa. Nevertheless, the redirect still doesn't work!) views.py def profile(request): profname = request.GET.get('profname', None) obj = User.objects.filter(username=profname) if not obj: print("I need this time to redirect to error page") else: print ("I need this to redirect home") redirect('home') return render(request, 'profile.html') html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <h1>jkkk</h1> <a id="butt" href="#">Get Data</a> </body> <script> $(document).ready(function(){ $("#butt").click(function(){ $.ajax({ type: "get", url: 'profile', datatype:'json', data: { 'profname': 'jillsmith', }, }); }); }); </script> urls.py urlpatterns = [ path('', views.explore, name='explore'), path('happening/profile/', views.profile, name='profile'), path('happening/', views.happening, name='happening'), path('home/', views.home, name='home'), path('happening/test/', views.test, name='test'), path('home/likes/', views.likes, name='likes'), ] -
Django Rest Framework Permissions and Ownership
I have two simple models class User(AbstractUser): pass class Vacation(Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) I am not really sure what is the scalable way of doing user permissions for Django Rest Framework. In particular: Users should only be able to see their own vacations On the /vacation endpoint, user would see a filtered list On the /vacation/$id endpoint, user would get a 403 if not owner Users should only be able to Create/Update vacations as long as they are the owners of that object (through Foreign Key) What is the best way to achieve this in a future-proof fashion. Say if further down the line: I add a different user type, which can view all vacations, but can only create/update/delete their own I add another model, where users can read, but cannot write Thank you! -
django app crashing on heroku TypeError: expected str, bytes or os.PathLike object, not function
my django app wont run on heroku and I cant figure out why. I get the following error code from heroku: 2019-02-19T17:36:16.022570+00:00 app[web.1]: TypeError: expected str, bytes or os.PathLike object, not function and then when I navigate to the site I get this: 2019-02-19T17:37:21.630743+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=full-stack-frameworks-django.herokuapp.com request_id=9d5b7ef6-790f-4584-921a-d1392842c93a fwd="109.78.21.112" dyno= connect= service= status=503 bytes= protocol=https and This is my settings.py file Django settings for IssueTracker project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # from dotenv import load_dotenv import psycopg2 import dj_database_url DATABASE_URL = os.environ['DATABASE_URL'] conn = psycopg2.connect(DATABASE_URL, sslmode='require') # WHITENOISE_USE_FINDERS = True # dotenv_path = os.path.join(os.path.dirname(__file__), '.env') # load_dotenv(dotenv_path) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'home', 'accounts', 'blogposts', 'tickets', 'payments', … -
Authentication with Django rest-auth works properly only with a superuser. In other cases I get - Unable to log in with provided credentials
Any ideas why rest-auth authentication works properly only with a superuser? When I try to log in user without staff and superuser permission I get the error shown below. During registration the user is created properly. { "non_field_errors": [ "Unable to log in with provided credentials." ] } -
Where is a CloudSigma Django source code?
Where is a CloudSigma Django source code??? Please, give me a CloudSigma Django source code, with API, etc. And also give me a CloudSigma WebApp source code. Thank you. -
save a generic collection in mongodb with flask or django
I´m creating a rest service that client will send a json file with collection name and datas. Previously i will not know the collection name and data types, so, I can´t create a model file for this. How mongodb accepts any kind of data, I just wanna create the colletion, if it doesn´t exist, and save datas in that. Any one can help me? -
Host two different projects django
I'm setting up a django web application and I'm using github for version management. So I need a testing page. How do I achieve this? I've found this question: Is it possible to host multiple django projects under the same domain? But it's 6 years old, I would prefer to host it under a sub-domain and I have no idea what the answer is talking about, since I'm new to Django. -
context isnt being read in the template
the if statement in the html code is not working at all the likes are getting sent through the like button but the button text isnt changing I tried different ways of passing context but none of them are working can I get any help or directions actually the button is displayed as like no matter weather the post is liked or not the same is happening in the post list view views.py from django.shortcuts import render,get_object_or_404 from django.views.generic import ListView from .models import Blog from django.http import HttpResponseRedirect class BlogsList(ListView): model=Blog template_name='blog/home.html' context_object_name='blogs' ordering=['-date_posted'] def like_post(request, blog_id): post = get_object_or_404(Blog, id=blog_id) is_liked=False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked=False else: post.likes.add(request.user) is_liked=True context={ 'is_liked':is_liked } return HttpResponseRedirect(Blog.get_absolute_url(blog_id)) def post_detail(request, id): post=get_object_or_404(Blog, id=id) context={ 'post':post,} return render(request, 'blog/post_detail.html',context) def check_liked(request): post = get_object_or_404(Blog, id=blog_id) is_liked=False if post.likes.filter(id=request.User.id).exists(): is_liked=True else: is_liked=False context={ 'is_liked':is_liked } return render(request, 'blog/post_detail.html',context) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Blog(models.Model): title=models.CharField(max_length=100) content=models.TextField() date_posted=models.DateTimeField(default=timezone.now) author=models.ForeignKey(User, on_delete=models.CASCADE) likes=models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title def get_absolute_url(blog_id): return reverse('post-detail',args=[str(blog_id)]) urls.py from django.urls import path from . import views urlpatterns=[ path('',views.BlogsList.as_view(),name='blog-home'), path('<int:blog_id>/like/', views.like_post, name='like_post'), path('post/<int:id>/', views.post_detail, name='post-detail'), ] post_detail.html < article class="media content-section"> <img … -
Django template, embed Bokeh plot via JSON item
I need to embed Bokeh plot via JSON item embedding. http://bokeh.pydata.org/en/latest/docs/user_guide/embed.html#json-items Please advise how this javascript part (made for Flask) should be converted for use in Django templates: <script> fetch('/plot') .then(function(response) { return response.json(); }) .then(function(item) { Bokeh.embed.embed_item(item); }) </script>