Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why PyCharm Terminal returnung different results?
Here is similar question pycharm terminal and run giving different results as you may see there was problem with Python versions. Here what I have: (difference in the last lines output) Ubuntu Terminal: ***@***:~/Documents/Coding/Django/myfirst$ python3 manage.py shell Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from articles.models import Article, Comment >>> a = Article.objects.get(id = 1) >>> a <Article: How to...?> >>> a.comment_set.all() <QuerySet [<Comment: John>, <Comment: Jack>, <Comment: Nelson>, <Comment: Bill>]> PyCharm Terminal: ***@***:~/Documents/Coding/Django/myfirst$ python3 manage.py shell Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from articles.models import Article, Comment >>> a = Article.objects.get(id = 1) >>> a.id 1 >>> a.article_Title 'How to...?' >>> a.comment_set.all() <QuerySet [<Comment: Comment object (1)>, <Comment: Comment object (2)>, <Comment: Comment object (3)>]> So it`s returning id of Comment instead of Name. Many thanks for any advice! -
django charField not accepts numbers
I'm new to django and i was testing CURD and it worked correctly till i found something weird i have charfield which not accepting any numbers and showing an error when i get all records Reverse for 'updateUser' with arguments '('uuu1',)' not found. 1 pattern(s) tried views.py def signup(request): form = UserForm() if request.method == 'POST': # fullname = request.POST['fullname'] form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = UserForm(request.POST) else: form = UserForm(request.POST) context = {'form':form} return render(request,'singup.html',context) def updateUser(request,fullname): user = User.objects.get(fullname__icontains=fullname) form = UserForm(instance=user) if request.method == 'POST': form = UserForm(request.POST, instance=user) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request,'singup.html',context) def getAllUsers(request): print("getAllUsers") thesearchValue = '' if 'SearchValue' in request.GET: thesearchValue = request.GET['SearchValue'] print(thesearchValue) print(request.GET['SearchValue']) allUsers = User.objects.filter(fullname__icontains=thesearchValue)#all() # return render(request,'getUsersInfo.html',{'allUsers':allUsers}) return render(request,'getUsersInfo.html',{'allUsers':allUsers}) else: print("Empty") allUsers = User.objects.all() return render(request,'getUsersInfo.html',{'allUsers':allUsers}) def deleteUser(request,fullname): print('delete the user') todelete = User.objects.filter(fullname=fullname) todelete.delete() return redirect(getAllUsers) Template <form method="GET"> {% csrf_token %} <div class="input-group"> <input type="text" class="form-control" placeholder="Search this blog" name="SearchValue"> <div class="input-group-append"> <button class="btn btn-secondary" type="button"> <i class="fa fa-search"></i> </button> </div> </div> </form> <table class="table table-bordered"> <thead> <tr> <th>Name</th> <th>Department</th> <th>Phone</th> <th>Actions</th> <th>Actions</th> </tr> </thead> <tbody> {% for x in allUsers%} <tr> <td>{{x.fullname}}</td> <td>{{x.email}}</td> <td>{{x.Resp}}</td> <td> <form … -
I installed a package outside virtual environment but cannot use it in the virtual environment
I've installed the package Pillow outside the virtual environment created using pipenv. But when I try to make migrations for my django project in this environment, it says Pillow is not installed and asks to install it. I think I installed pillow globally but it is not accessible by the pipenv virtual environment. I'm using python 3.8 and use sublime3 as editor. -
Check if object has relation with other in ManyToMany field and aggregate field
I have a couple models as follows: class Student(models.Model): name = models.CharField() classes = models.ManyToManyField(Class, related_name="students") class Class(models.Model): nombre = models.CharField What I need is a way such that, when querying students in certain class, instead of just returnig the students enrolled in that class, it returns a list of all the students, each one with an aggregated field indicating if such student is enrolled in that class, e.g.: [{'name':'student A', 'enrolled_in_physics':True}, {'name':'student B', 'enrolled_in_physics':False}] I think it can be achieved through F() expressions along with ExpressionWrapper, but have no idea of how implement them; additionaly, the documentation and the examples are not very noob-friendly. Any help is appreciated, thanks!. -
Please share what can be achieved using Django Middleware?
1)Cross site script validation 2)Connect database for CRUd operations 3)User authentication 4)Used for creating greaphical images I feel like 1 and 3 can be done, but please give suggestion if I am correct or not -
https module post request does't send data to django server from dialogflow fulfillment
I want to use post method for sending data to django server from dialogflow fulfillment. POST request completes successfully giving statusCode 200, but doesn't send any data. Dialogflow Fullfilment Code const https = require('https'); const data = JSON.stringify({ name: 'John Doe', job: 'Content Writer' }); const options = { hostname: 'my-url.com', method: 'POST', port:443, headers: { 'Content-Type': 'application/json', 'Content-Length': data.length } }; const req = https.request(options, res => { console.log(`statusCode: ${res.statusCode}`); let response = ''; res.on('data', (chunk) => { response+=chunk; }); res.on('end', () => { console.log('Body: ', JSON.parse(response)); }); }).on('error', error => { console.error(error); }); req.write(data_string); req.end(); Dialogflow responses with status 200 in firebase logs, but Django doesn't get any data from post request. Django Code def test_func(request): print(request.POST) return JsonResponse({'Response': request.POST}) Django server logs return empty query list <QueryDict: {}> note: I removed CsrfViewMiddleware in django settings, for just testing purpose -
How to access the ppts stored in the media folder in to views.py to perform certain operations in django
*i have added the code in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') also in urls.py from django.contrib import admin from django.urls import path from django.urls import include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('cmp.urls')), path('', include('usr.urls')), path('', include('com.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) the code written in views.py is import os from pptx import Presentation from django.conf import settings settings.configure() your_media_root = settings.MEDIA_ROOT+'media/input/Bebras_Best_of_school.pptx' prs = Presentation(your_media_root) title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title subtitle = slide.placeholders[1] title.text = "Hello, World!" subtitle.text = "python-pptx was here!" prs.save('test.pptx') and the error i m getting is pptx.exc.PackageNotFoundError: Package not found at 'media/input/Bebras_Best_of_school.pptx' can you please help me* -
I wrote a code in Jupiter for visualization of graph. That code I want to write in Django. But I face an Issue while is properly run in Jupiter
import numpy as np import pandas as pd import matplotlib.pyplot as plt import COVID19Py covid19 = COVID19Py.COVID19() covid19 = COVID19Py.COVID19(data_source="jhu") latest = covid19.getLatest() location = covid19.getLocationByCountryCode("IN") loc_data=location[0] virusdata=dict(loc_data) loc_data=location[0] virusdata=dict(loc_data['latest']) names=list(virusdata.keys()) values=list(virusdata.values()) plt.bar(range(len(virusdata)),values, tick_label=names) plt.title('COVID-19 Analysis') plt.show() -
Django - App Engine - Cloud SQL (PostgreSQL) - OperationalError: could not connect to server: Connection refused
I have Django deployed to App Engine that's connected to Cloud SQL (PostgreSQL) instance. I keep getting the following errors: OperationalError: could not connect to server: Connection timed out and OperationalError: could not connect to server: Connection refused app.yaml # [START django_app] runtime: python37 service: prestige-worldwide handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto # [END django_app] settings.py - DATABASE configuration ALLOWED_HOSTS = ['app-engine url','127.0.0.1'] DATABASES = { 'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'instance public ip address', 'PORT': 'ip address host',}} It works fine locally with Cloud SQL, but doesn't work when deployed to App Engine. -
Django, internationalization and localization. How to translate dynamic content in the best possible way?
I have a news tab on my website. News is parsed from another site, so I can't translate all this content manually in my django.po file. So how can I do it in some other way? Also, i want to use language switcher, but this {% trans 'value' %} is so awful and bad, so it can translate words like 'Go/Change/English', only uppercase, only one-two words, and...that's it. Otherwise, I need to translate everything manually in my django.po file. But I can't do this because the content is constantly changing. Maybe I can somehow connect something like Google Translate language switcher to my site? If you know how to translate dynamic content in the best possible way, then I need your advices, suggestions, and recommendations, because i don't know how to do that in the best way. Thanks, any help will be invaluable. -
Image Text overlay where image is cropped to text are
I want to create a div that contains an img tag with the divs background image (so without CSS background property). This div also contains a child div with a dynamic amount of text. How can I make the background image or parent div crop itself according to the amount of text? this is my code atm: <div class="card bgslide text-center "> <div class="card-body text-white p-2"> {% if text.textList %}<div class="lecturer_note_overlay" ID="t2_{{text.id}}"><span class="text_title">{{text.title}}</span><br>{{ text.textList|safe|urlizetrunc:50 }}</div>{% endif %} </div> <img src="{{ text.image|thumbnail_url:'slides' }}" class="card-image-top transparent-image"/> <p></p> </div> -
Python, in project imports are not recognized
I have a Django project that I restructured. Since I did that all the imports doesn't work, but it's not consistent. For example, In my settings.py file: # triangulationapi/triangulationapi/setting.py from Project_Level.DataBase.DataBaseConsts import POSTGRESQL_CONNECTION This line doesn't raise errors (even though pycharm treats it as faulty) . but this line on one of the apps: from django.db import models from django.utils import timezone from ProjectLevel.APIConsts.Consts import AREAS raises error: from ProjectLevel.APIConsts.Consts import AREAS ModuleNotFoundError: No module named 'ProjectLevel' Using relative imports doesn't work as well: ..APIConsts.Consts import AREAS from ..APIConsts.Consts import AREAS ValueError: attempted relative import beyond top-level package from triangulationapi.Project_Level.APIConsts.Consts import AREAS doesn't work as well from triangulationapi.Project_Level.APIConsts.Consts import AREAS ModuleNotFoundError: No module named 'triangulationapi.Project_Level' My structure: ├── triangulationapi │ ├── hashers.py │ ├── __init__.py │ ├── KnownLocation │ ├── landingpage │ ├── manage.py │ ├── messages.pot │ ├── Project_Level │ ├── requirements.txt │ ├── SecondGDT │ ├── static │ ├── templates │ ├── ThreeLocations │ ├── triangulationapi └── ven -
How to sort on Long field in solr using django haystack by specifying the sort variable in url
My url looks like localhost:8000/searchManagement/search/t/age_group_to__gte=35&sort=age_group_from asc Here I am.trying to sort on Long field 'age_group_from' but its not working. Can someone help me please? -
how to use href links in django
I have a Django project like this: -project -templates file.html -project -app views.py How do I get to call a function in views.py from the file.html in an <a href="..."> link </a>statement? I already tried <a href="{% url '..app.views.function' %}">Link</a>, but that doesn't work. thx for your help and stay healthy! -
Is it possible to initialize a django OneToOneField without changing the related side until save?
I have a model that has a OneToOneField to itself which creates chains of this model. class Foo(models.Model): parent = models.OneToOneField('Foo', related_name='child', null=True, blank=True, on_delete=models.CASCADE) ... I want to build chains of these and replace parts by creating potential shorter chains that are presented as options from which one or none can selected. base = Foo() base.save() old_tail = Foo(parent=base) old_tail.save() option_1 = Foo(parent=base) Foo(parent=option_1) option_2 = Foo(parent=base) Foo(parent=option_2) It seams like I incorrectly assumed that the reference base.child is not updated until one of the options is saved. I noticed this because base.child now points to option_2. Is it possible to create the behavior that I desire? I.e. so that I can create potential instanced of Foo with parent=base but without actually changing base.child until I save them? -
How to pass a value from the view to a ModelForm
I'm trying to get the Id to filter the choices item to see. After several tutorials and docs, I'm still not get through... Here is the model: class CheckUpList(models.Model): title = models.CharField(max_length=150) task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='checkuplist') done = models.BooleanField(default=False) def __str__(self): return self.title Here is the form: class MakeChecklistDone(forms.ModelForm): def __init__(self, task, *args, **kwargs): super(MakeChecklistDone, self).__init__(*args, **kwargs) #title = forms.CharField(max_length = 32) choices = forms.ModelMultipleChoiceField( widget = forms.CheckboxSelectMultiple(), queryset=CheckUpList.objects.all().filter(done=False, **task=??**) ) class Meta: model = CheckUpList fields = ['choices', ] I'm using the bellow view : def task_detail(request, pk): template_name = 'task/task-detail.html' task = Task.objects.get(pk=pk) ... if request.method == 'POST': ... else: form_checkUpList = MakeChecklistDone(request.POST, **initial={'task': 11 }**) But it seems I doing something wrong... Any helps will be marvellous. -
graphql.error.located_error.GraphQLLocatedError: connection_resolver() missing 1 required positional argument: 'info'
I'm trying to set permissions for my django-graphql(graphene) project using this package. According to it's doc, I have set the following configuration to control the all_dormitories query: from graphene_permissions.mixins import AuthNode, AuthFilter from graphene_permissions.permissions import AllowAuthenticated, AllowAny class DormitoryNode(AuthNode, DjangoObjectType): permission_classes = (AllowAuthenticated,) class Meta: model = Dormitory filter_fields = { 'name': ['exact', 'icontains', 'istartswith'], } interfaces = (graphene.relay.Node,) class AuthenticatedFilter(AuthFilter): permission_classes = (AllowAuthenticated,) class DormitoriesQuery(graphene.ObjectType): all_dormitories = AuthenticatedFilter(DormitoryNode) But when I send request to this query it responds as follows: { "errors": [ { "message": "connection_resolver() missing 1 required positional argument: 'info'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "allDormitories" ] } ], "data": { "allDormitories": null } } Anyone knows what's the problem with my code? Note: I have replaced AllowAuthenticated with AllowAny and the response was the same. -
Django form - JQuery - chained fields - verification fails (is_valid function)
In my Django form I have three fields that are linked to each other (similar to the trio country- state-city which is often given as an example on the web). Visually it works thanks to jQuery scripting. The #id_division field interacts with #id_section which interacts with #id_cellule which interacts with #id_superieur. {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block css %} {% endblock css %} {% block title %} <title>Edit user</title> {% endblock title %} {% block toolbar %} {% endblock toolbar %} {% block content %} <br> <form method="POST" class="bootstrap4" id="id-StaffForm" data-sections-url="{% url 'ajax_load_sections' %}" data-cellules-url="{% url 'ajax_load_cellules' %}" data-superieurs-url="{% url 'ajax_load_superieurs' %}" novalidate> {% csrf_token %} {% crispy staff_form %} </form> {% endblock content %} {% block script %} <script> var sections_url = $("#id-StaffForm").attr("data-sections-url"); var cellules_url = $("#id-StaffForm").attr("data-cellules-url"); var superieurs_url = $("#id-StaffForm").attr("data-superieurs-url"); var divisionId = $("#id_division").val(); var sectionId = $("#id_section").val(); var celluleId = $("#id_cellule").val(); $('#id_division').change(function () { divisionId = $(this).val(); $("#id_section").html(''); // initialize an AJAX request for SECTION $.ajax({ // set the url of the request url: sections_url, // add the division id to the GET parameters data: { 'division': divisionId }, // `data` is the return of the `load_sections` view function … -
Django Chache - Update when model changed
I can't seem to find any tutorial on how to do this. So, I basically want to add caching to my Django project. I made a blog view, that should be cached and updated only if the model got changed since last caching. How do I do this? -
Django submit form when browser is refreshed for multiple form
There is a lot of similar question. But my problem is slightly different. In a view, I am using multiple forms, for that, I am using formset and normal form.here is my view: class CreateInvoice(TemplateView): template_name = 'product/create_invoice.html' product_list = Product.objects.get_all_product() ItemFormSet = formset_factory(ItemForm, formset=BaseItemFormSet, extra=0) def get_context_data(self, **kwargs): if 'items' not in kwargs: kwargs['items'] = self.ItemFormSet() if 'order' not in kwargs: kwargs['order'] = OrderForm() kwargs['product_list'] = self.product_list return super().get_context_data(**kwargs) def post(self, request): item_formset = self.ItemFormSet(request.POST) order_form = OrderForm(request.POST) if order_form.is_valid() and item_formset.is_valid(): order = order_form.cleaned_data items = item_formset.cleaned_data order['sold_by'] = request.user order_id = Order.objects.crate_new_order(order=order, items=items) return HttpResponseRedirect(self.render_to_response(self.get_context_data(pos_invoice=generate_pos_invoice(), order_id=order_id))) else: return HttpResponseRedirect(self.render_to_response(self.get_context_data(items=item_formset, order=order_form,))) If forms are not valid then I need to render the same page with error messages. If forms are valid then also need to render the same page with the HTML receipt string and the extra data. But here the problem is if the browser is refreshed (like pres crtl+f5) then the same forms are submitted again. From googling I came to know that this problem is created for I am using render instead of a redirect. Here is the link of the question from where I came to know this: Django form submit again on refresh … -
What is the best way to use other models as dynamic fields in django?
I'm working on an app that basically functions like a gradebook + online exam service. In an analog gradebook, or in one on a spreadsheet, teachers typically have a row entry for each student. Then, they make a new column for every exam, and fill in all the students' grades for that exam. So I want to be able to add and remove exams at will, and also to show the user things like "all student grades for this exam" or "all exam grades for this student". Each exam model is built from a list of (ManyToMany) Question models. Ideally, I'd also like to be able to track individual questions the same way I do exams: get a list of which students got them right, etc. Is there a best or standard way to do these things? ManyToManyFields seem a little awkward to me and I was wondering if I was missing something. -
url getting doubled when opening a link from the home page.(django)
On clicking the 2nd item in the list it opens the events.html page but the url shows: http://127.0.0.1:8000/events/events/ instead of http://127.0.0.1:8000/events Home page code: <li><a href="#">HOME</a></li> <li><a href="{% url 'events' %}">EVENTS</a></li> <li><a href="#">REGISTERED TEAMS</a></li> <li><a href="#">CONTACT US</a></li> Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home_page, name='home_page'), path('hackathon_register/',views.hackathon_register,name='hackathon_register'), path('events/',views.events,name='events') ] views.py def events(request): return render(request,'testapp/events.html',{}) -
Replace white space with hyphens in Django URL
I saw that a lot of websites (including stackoverflow) will have the title of the questions/articles in the URL with hyphens and I am trying to achieve the same for a small blog app using Django, however, so far I have been having 0 success. My models.py look as follow: class Post(models.Model): title = models.CharField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + '|' + str(self.author) Defining the URL as: urlpatterns = [ # re_path(r'^post/(?P<title>[\w\-]+)/$', PostView.as_view(), name='post_details'), path('post/<slug:title>', PostView.as_view(), name='post_details'), ] and adding the following to the views.py: class PostView(DetailView): model = Post slug_field = slugify('title') slug_url_kwarg = slugify('title') template_name = 'post_details.html' resulted no success, as titles which have hyphens result a Page not found (404). As seen from the urls.py, I have tried both using a regular expression and the newer Django 2.0+ syntax and both giving the same result. Is my mistake in the URL definition or am I not introducing the slug correctly to the view? -
Django: How to automatically set correct media folder permissions?
I am running a Django application using Apache webserver. The media directory is located in /var/www/app/media/. Owner of that directory is www-data:www-data, so that Apache can read / write to it. The problem now is that when I run ./manage.py migrate and a new sub-folder in the media directory is created when I add a new FileField to a model, the owner of that directory is the user running that migrate command and I have to fix the owner of that new folder, otherwise Apache can't write to it and I am getting a Permission denied error. How can I set permissions to the folder /var/www/media/that user www-data can write to any new subfolder, even when that subfolder is created by another user ? -
I am a newbie please help i keep getting error You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
i keep getting this message when i run "git push heroku master" remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. remote: ! Error while running '$ python manage.py collectstatic --noinput'. Settings.py import django_heroku import os # 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 = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'pytalk.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, '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', ], }, }, ] WSGI_APPLICATION = 'pytalk.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 = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE …