Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-extra-views for many-to-many relationship
Using Django Extra Views - Django Extra Views I have a form and Skill model has Many to Many relationship with Profile. The error I am getting is Unknown field(s) (title) specified for Skill_profile How would I use the formsets with many-to-many relationship? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=50, blank=True) description = models.TextField(blank=True) avatar = models.ImageField(blank=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse('profile') class Skill(models.Model): profile = models.ManyToManyField(Profile, related_name='skills', blank=True) title = models.CharField(max_length=100, blank=True) def __str__(self): return self.title views.py class ProfileSkillInline(InlineFormSetFactory): model = Skill.profile.through fields = ['title'] class SkillInline(InlineFormSetFactory): model = Skill inlines = [ProfileSkillInline] # fields = ['title'] # initial = [{'title': 'Enter Skill'}] factory_kwargs = {'extra': 1, 'max_num': None, 'can_order': False, 'can_delete': True} prefix = 'skill_formset' class ProfileUpdateView(UpdateWithInlinesView): model = Profile inlines = [ProfileSkillInline, ProjectInline] fields = ['full_name', 'description', 'avatar'] template_name = 'profile_edit.html' def get_queryset(self): return Profile.objects.get(user=self.request.user) def get_object(self, queryset=None): return self.get_queryset() -
AWS EB WSGI path refers to a file that doesn't exist
I have a Django app that I'm trying to deploy to AWS Elastic Beanstalk but I'm getting the following error during the deployment: 2019-04-14 20:50:20 ERROR Your WSGIPath refers to a file that does not exist. I have updated the wsgi settings following this guide: aws:elasticbeanstalk:container:python: NumProcesses: '1' NumThreads: '15' StaticFiles: /static/=static/ WSGIPath: Appname/wsgi.py aws:elasticbeanstalk:container:python:staticfiles: /static/: static/ The .ebextensions directory along with the elasticbeanstalk, the main django project folder (containing the settings and wsgi files) are all in the same directory: .ebextensions elasticbeanstalk Appname - __init__.py - settings.py - urls.py - wsgy.py What could be causing the wsgi file to not be found? -
Issues with value duplication in queryset filters
I am working on a web-application using django, and I would like to be able to return a queryset filter for a model that has no duplication. I know that distinct() exists but I do not know how to apply it on my code. I would like to return a list of cities from this queryset but not show duplicates. I have already tried using if statements where the for loop is for the returned queryset with no success. class StoreFilter(django_filters.FilterSet): class Meta: model = Store fields = { 'city': ['icontains'], } def my_store_filter(self, queryset, city, value): return queryset.filter(**{ city: value, }) -
How to fix "Not Found" problem for displaying images?
I'm preparing a blog component of a site, it is created inside an app of a project. It seems that there is no problem except the images are not displayed. while running, all things are OK, but just the image "alt" is displayed instead of the image. I have images without problem in other pages of this project. There is a report on Terminal: "Not Found: /article/static/images/growth_EWAl68g.png [14/Apr/2019 17:44:38] "GET /article/static/images/growth_EWAl68g.png HTTP/1.1" 404 6164" As you can see, Django uses a false address (static folder is located in root of projects) to access the images. class BlogArticle(models.Model): title = models.CharField(max_length=150) headline = models.CharField(max_length=300) body = models.TextField() post_image = models.ImageField(upload_to ="static/images") date = models.DateTimeField(auto_now_add=True) author = models.CharField(max_length=100) def __str__(self): return self.title class ArticleListView(ListView): model = BlogArticle template_name = 'article_list.html' urlpatterns = [ path('', views.HomeView, name= 'home'), path('article/', views.ArticleListView.as_view(), name='article_list'), path('article/<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail'), . . .] from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('contactus', include('sendemail.urls')), path('', include('myapp.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) {% block content %} <div <div class="container mt-5 bg-light"> {% for article in object_list %} <div class="form-row"> <div class="form-group col-sm-9 "> … -
How to use related objects reference correctly Django
I have these models: from django.db import models from django.conf import settings from django.core.validators import validate_comma_separated_integer_list from django.core.exceptions import ImproperlyConfigured from django.utils.timezone import now from model_utils.managers import InheritanceManager from mdlteorico.models import SubDominio import json class CertificacaoManager(models.Manager): def search(self, query): return self.get_queryset().filter( models.Q(name__icontains=query) | models.Q(description__icontains=query) ) class Certificacao(models.Model): name = models.CharField('Nome', max_length=100) slug = models.SlugField('Atalho') description = models.TextField('Descrição simples', blank=True) start_date = models.DateField('Data de início', null=True, blank=True) image = models.ImageField(upload_to='certificacoes/images', verbose_name='Imagem', null=True, blank=True) created_at = models.DateTimeField('Criado em', auto_now=True) updated_at = models.DateTimeField('Atualizado em', auto_now=True) def get_absolute_url(self): from django.urls import reverse return reverse('certificacoes:certificados', kwargs={'slug': self.slug}) objects = CertificacaoManager() def __str__(self): return self.name class Meta: verbose_name = 'Certificação' verbose_name_plural = 'Certificações' ordering = ['name'] class Certificado(models.Model): name = models.CharField(max_length=50) slug = models.SlugField('Atalho') description = models.TextField('Descrição simples', blank=True) certificacao = models.ForeignKey(Certificacao, on_delete=models.CASCADE, related_name='certificacao') quantidade_questoes = models.PositiveIntegerField(blank=True, null=True, verbose_name='Quantidade máxima de questões') created_at = models.DateTimeField('Criado em', auto_now=True) updated_at = models.DateTimeField('Atualizado em', auto_now=True) def __str__(self): return self.name class Meta: verbose_name = 'Certificado' verbose_name_plural = 'Certificados' ordering = ['name'] class Situacao(models.Model): enunciado = models.TextField(max_length=2000, blank=True, verbose_name='Enunciado') certificado = models.ManyToManyField(Certificado, related_query_name='certificado') def __str__(self): return '{}...'.format(self.enunciado[:80]) class Meta: verbose_name = "Situação" verbose_name_plural = "Situações" class Questao(models.Model): subdominio = models.ManyToManyField(SubDominio) situacao = models.OneToOneField(Situacao, on_delete=models.CASCADE, related_query_name='situacao') questao = models.TextField(max_length=1000, blank=True, verbose_name='Questão') objects … -
No Entry Matches Query Django website, but could get it in shell
Models class Category(models.Model): class Meta(): verbose_name_plural = "Categories" cat_name = models.CharField(max_length=50) description = models.TextField() def __str__(self): return f"{self.cat_name}" class Forum(models.Model): class Meta(): verbose_name_plural = "Forums" category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="forums") forum_name = models.CharField(max_length=50) description = models.TextField() def __str__(self): return f"{self.forum_name}" URL path('cat/<int:pk>/', CategoryDetailView.as_view(), name="catview") Views class CategoryDetailView(DetailView): model = Category template_name = 'forums/index.html' context_object_name = 'forums' def get_queryset(self, *args, **kwargs): queryset = Category.objects.get(pk=self.kwargs['pk']).forums.all() return queryset HTML <div class="row"> <div class="bg-success rounded-top border border-dark" style="width:100%; padding-left:8px;"> {{forums}} </div> </div> When i got to the link cat/2/ i get the message: "No forum found matching the query". I could get the query to match in the shell just fine. shell commands >>> from forums.models import Category >>> aa = Category.objects.get(pk=2).forums.all() >>> aa <QuerySet [<Forum: testforum>]> -
Do I have to Add All Fields to ModelForm Even If Only One of Them Needs User Input?
Only one field needs user input. Others depend on that one field and are programatically populated before saving the form. Adding the other fields to the ModelForm and making them hidden is the only solution or is there a better way? class Sentence(models.Model): sent = models.CharField(max_length=150) # Only this field needs user input sent_correct = models.CharField(max_length=300, blank=True) msg_list = ArrayField(models.CharField(max_length=500), blank=True, default=list) pub_date = models.DateTimeField(default=timezone.now) class SentenceForm(ModelForm): class Meta: model = Sentence fields = ['sent'] # I want to avoid attribute error in the view and programatically populate the fields before saving the form -
How to show code snippet in django template, "|safe" filter not helps
I'm trying to make app like gist.github.com. After saving code snippets they looks in like long string. I tryed different filters like "safe, escape ... etc". Nothing helped me. In database code looks like def asd(a): return a+2 asd(2) This is my template code {{ s.code|escape }} Result is: def asd(a): return a+2 asd(2) -
Project bootcamp have error in Javascript, as JS not working as intended
I'm using an Open source project Bootcamp, it has a Question, Answer, and Vote model, it's logic is kind of like StackOverflow, it's logic is working correctly but it's giving some bug in javascript. View to handle votes def question_vote(request): """Function view to receive AJAX call, returns the count of votes a given question has recieved.""" question_id = request.POST["question"] value = None if request.POST["value"] == "U": value = True else: value = False question = Question.objects.get(pk=question_id) try: question.votes.update_or_create( user=request.user, defaults={"value": value}, ) question.count_votes() return JsonResponse({"votes": question.total_votes}) except IntegrityError: # pragma: no cover return JsonResponse({'status': 'false', 'message': _("Database integrity error.")}, status=500) Javascript code to call ajax function $(".question-vote").click(function () { // Vote on a question. var span = $(this); var question = $(this).closest(".question").attr("question-id"); vote = null; if ($(this).hasClass("up-vote")) { vote = "U"; } else { vote = "D"; } $.ajax({ url: '/qa/question/vote/', data: { 'question': question, 'value': vote }, type: 'post', cache: false, success: function (data) { $('.vote', span).removeClass('voted'); if (vote === "U") { $(span).addClass('voted'); } $("#questionVotes").text(data.votes); } }); }); HTML code for only voting buttons <div class="col-md-1"> <div class="question-info options"> <h3 class="{% if question.has_answer %}bg-success text-white{% endif %}">{{ question.count_answers }}</h3> <small class="text-secondary">{% trans 'Answers' %}</small> <i id="questionUpVote" class="fa fa-chevron-up vote … -
collectstatic doesn't ignore specified files
i'm having some trouble figuring out how to manage my scss files. Here's what my folder structure looks like: manage.py ├── myWebsite │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── projects │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── static │ │ └── projects │ │ └── css │ │ ├── index.css │ │ ├── scss │ │ │ └── survey.scss │ │ └── tribute.css │ ├── templates │ │ └── projects │ │ ├── base.html │ │ ├── documentation.html │ │ ├── index.html │ │ ├── portfolio.html │ │ ├── product.html │ │ ├── survey.html │ │ └── tribute.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── requirements.txt └── staticfiles └── projects └── css └── scss ├── survey.css └── survey.css.map I'd like to keep my .scss files inside the static/{app_name}/css/scss folder of each app. Those are later compiled inside the staticfiles folder which is in the project root. That same folder is the root for collectstatic, which is run when deploying on the server (AWS EB) 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" Since I'm using Django … -
No matching distribution found for Django==2.2
I am deploying a django app on a digital ocean droplet server that I developed using Django version 2.0. Using Putty to SSH into my ubuntu server, I try to upgrade using pip install Django==2.2. I get the following error message: Could not find a version that satisfies the requirement Django==2.2 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, … -
Project bootcamp have error in Javascript, as JS not working as intended
I have put up an issue on Github in January in a Django Bootcamp project, the issue link is this, but I'm unable to get a solution for it so if anyone can help me regarding this that would be highly appreciated. The source code for this project is at Bootcamp project. The explanation of the issue at issue link. The source code for the javascript file at here. The source code for views file at here. and the source code for template is at here. -
refernceing a class from it's object in python
i know it may be weird, but let me explain class Comment(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments') comment = models.TextField() target_ct = models.ForeignKey(ContentType, on_delete=models.CASCADE) target_id = models.PositiveIntegerField() target = GenericForeignKey('target_ct', 'target_id') second_level_comment = GenericRelation(Comment, content_type_field='target_ct', object_id_field='target_id') def __str__(self): return self.comment[:40] in the code above I have a generic relation from django and I want to reference to the comment from a comment I can make it using filter as it's working but i can't find a solution to put GenericRelation field with a reference to the comment class itself. I want something like self.__class__ which here doesn't make any sense of course -
TypeError trying to uploading a image with ImageField in django
i am receiving this error while i am trying to upload a image with ImageField: TypeError at /admin/article/articulo/7/change/ not all arguments converted during string formatting Request Method: POST Request URL: http://127.0.0.1:8000/admin/article/articulo/7/change/ Django Version: 2.1.5 Exception Type: TypeError Exception Value: not all arguments converted during string formatting Exception Location: C:\Users\HOME\ProyectosDjango\weMarket\apps\article\models.py in upload_location, line 6 This is a part from the models.py with the ImageField: def upload_location(instance, filename): return "static/img/" %(instance.id, filename) class Articulo(models.Model): ... nombre_imagen=models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") width_field=models.IntegerField(default=0) height_field=models.IntegerField(default=0) ... def __str__(self): return "("+str(self.id)+") " + self.nombre_producto This is a part from the forms if you need it: class ArticleForm(forms.ModelForm): class Meta: model = Articulo fields = [ 'nombre_imagen', 'nombre_producto', 'id_clasificacion_fk', 'Descripcion', 'long_descripcion', 'precio', 'cantidad', ] And the HTML with the form: <div class="row"> <div class="col-md-10"> <form method="post"> <h5 class="mb-3">Agregar artículo</h5> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-lg btn-success">Guardar cambios</button> </form> </div> <div class="col-md-2"> <img src="{% static 'img/handpen.png'%}"width="350px" height="310px" /> </div> </div> If anyone can help me let me know. Thank you!. -
Testing Celery Beat
i work on a celery beat task within a django project which creates Database entries periodically. I know so beacuse when i set the task up like this : celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab app = Celery("clock-backend", broker=os.environ.get("RABBITMQ_URL")) app.config_from_object("django.conf:settings", namespace="CELERY") app.conf.beat_schedule = { 'create_reports_monthly': { 'task': 'project_celery.tasks.create_reports_monthly', 'schedule': 10.0, }, } app.autodiscover_tasks() And start my project it really creates an object every 10 seconds. But what i really want to do is to set it up to run every first day of a month. To do so i would change "schedule": crontab(0, 0, day_of_month="1"). Here comes my actual problem : How do i test that this really works ? And by testing i mean actual (unit)tests. What I've tried is to work with a package called freezegun. A test with this looks like this : def test_start_of_month_report_creation(self, user_object, contract_object, report_object): # set time to the last day of January with freeze_time("2019-01-31 23:59:59") as frozen_time: # let one second pass frozen_time.tick() # give the celery task some time time.sleep(20) # Test Logic to check whether the object was created # Example: assert MyModel.objects.count() > 0 But this did not work. … -
CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/free/win-64/repodata.json.bz2>
I'm setting up the virtual enviornment of django for the first time. I've downloaded the anaconda library of python in my D drive. So initially I set up the path of python and conda(Scripts) manually in advance system settings. But now when I'm creating the enviornment using command conda create --name mydjang0 django the command prompt is showing an error like this- C:\Users\AABHA GAUTAM> conda create --name mydjang0 django Solving environment: failed CondaHTTPError: HTTP 000 CONNECTION FAILED for url https://repo.anaconda.com/pkgs/pro/win-64/repodata.json.bz2 Elapsed: - An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way. If your current network has https://www.anaconda.com blocked, please file a support request with your network engineering team. SSLError(MaxRetryError('HTTPSConnectionPool(host=\'repo.anaconda.com\', port=443): Max retries exceeded with url: /pkgs/pro/win-64/repodata.json.bz2 (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))')) -
My bootstrap accordion menu stopped working after I included require.js, how to resolve this?
I have a web built with django , which takes a jupyter notebook and renderes the notebook on the web. the notebook requires require.js and plotly.js as javascript libraries. I have an accordion menu built with bootstrap in my page, after including <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> the accordion menu stops opening and collapsing, and when I do remove these script tags they work again. this is the error I am getting in console: Uncaught Error: Mismatched anonymous define() module: function(){return function(){return function t(e,r,n){function i(o,s){if(!r[o]){if(!e[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=r[o]={exports:{}};e[o][0].call(u.exports,function(t){return i(e[o][1][t]||t)},u,u.exports,t,e,r,n)}return r[o].exports}for(var a="function"==typeof require&&require,o=0;o<n.length;o++)i(n[o]);return i}}()({1:[function(t,e,r){"use strict";var n=t("../src/lib"),i={"X,X div":"direction:ltr;font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;","X input,X button":"font-family:'Open Sans', verdana, arial, sans-serif;","X input:focus,X button:focus":"outline:none;","X a":"text-decoration:none;","X a:hover":"text-decoration:none;","X .crisp":"shape-rendering:crispEdges;","X .user-select-none":"-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;","X svg":"overflow:hidden;","X svg a":"fill:#447adb;","X svg a:hover":"fill:#3c6dc5;","X .main-svg":"position:absolute;top:0;left:0;pointer-events:none;","X .main-svg .draglayer":"pointer-events:all;","X .cursor-default":"cursor:default;","X .cursor-pointer":"cursor:pointer;","X .cursor-crosshair":"cursor:crosshair;","X .cursor-move":"cursor:move;","X .cursor-col-resize":"cursor:col-resize;","X .cursor-row-resize":"cursor:row-resize;","X .cursor-ns-resize":"cursor:ns-resize;","X .cursor-ew-resize":"cursor:ew-resize;","X .cursor-sw-resize":"cursor:sw-resize;","X .cursor-s-resize":"cursor:s-resize;","X .cursor-se-resize":"cursor:se-resize;","X .cursor-w-resize":"cursor:w-resize;","X .cursor-e-resize":"cursor:e-resize;","X .cursor-nw-resize":"cursor:nw-resize;","X .cursor-n-resize":"cursor:n-resize;","X .cursor-ne-resize":"cursor:ne-resize;","X .cursor-grab":"cursor:-webkit-grab;cursor:grab;","X .modebar":"position:absolute;top:2px;right:2px;","X .ease-bg":"-webkit-transition:background-color 0.3s ease 0s;-moz-transition:background-color 0.3s ease 0s;-ms-transition:background-color 0.3s ease 0s;-o-transition:background-color 0.3s ease 0s;transition:background-color 0.3s ease 0s;","X .modebar--hover>:not(.watermark)":"opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;","X:hover .modebar--hover .modebar-group":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;padding-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar.vertical":"display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;","X .modebar.vertical svg":"top:-1px;","X .modebar.vertical .modebar-group":"display:block;float:none;padding-left:0px;padding-bottom:8px;","X .modebar.vertical .modebar-group .modebar-btn":"display:block;text-align:center;","X [data-title]:before,X [data-title]:after":"position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, … -
disappeared slug in administration site
i have wrote this codes in admin.py @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ['title','slug','author','publish','status',] list_filter = ['status','created','publish','author',] search_fields = ['title','body',] prepopulated_fields = {'slug':('title',)} but when in administration site write some words as title like "this", "for", "as" and ... they wont write in slug field and disappeared what is the problem? -
Importing Python output into an HTML file
I've been experimenting with my Django site for a while now and I ran into one problem I can't seem to fix. So on one hand I have this code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("--headless") options.add_argument('--no-sandbox') options.add_argument('start-maximized') options.add_argument('disable-infobars') options.add_argument("--disable-extensions") url = 'https://old.reddit.com/r/Lain/new/' driver = webdriver.Chrome(chrome_options=options) driver.get(url) sub = WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "subscribers"))) onl = WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "users-online"))) def onlineCheck(): for s,o in zip(sub,onl): status = (s.text + ' susbscribed, ' + o.text + ' currently viewing') return status driver.quit() On the other, an empty HTML file. What I want to do is print out the output from the onlineCheck function to the HTML file. -
Python/django can't migrate on heroku
I have problem with migrate on heroku after 'heroku run python manage.py migrate' command I always have error and I don't known how to fix it. (venv) E:\Studia\advise\promotion>heroku run python manage.py migrate Running python manage.py migrate on ⬢ pro-motion... up, run.6349 (Free) Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/promotion/settings.py", line 27, in <module> DEBUG = config('DEBUG', default=False, cast=bool) File "/app/.heroku/python/lib/python3.6/site-packages/decouple.py", line 197, in __call__ return self.config(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/decouple.py", line 85, in __call__ return self.get(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/decouple.py", line 79, in get return cast(value) File "/app/.heroku/python/lib/python3.6/site-packages/decouple.py", line 50, in _cast_boolean raise ValueError('Not a boolean: %s' % value) ValueError: Not a boolean: True -
AttributeError at /dashboard/ 'NoneType' object has no attribute 'year'
I recently started to use django and python to work on my project but I can't solve this problem. Please help. The line started with "sales_by_months_ts =qss.time_series(start, end, interval='months')" display as an error when I run it in django. start, end = mindate['date__min'], maxdate['date__max'] sales_by_month_ts = qss.time_series(start, end, interval='months') MonthL = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', Dec'] months_dict="[" for t in sales_by_month_ts: monthobj_dict="{'month': '"+ t[0].strftime("%Y-%m") + "', 'incidents': '" + str(t[1]) + "'}," months_dict = months_dict + monthobj_dict months_dict = months_dict + "]" -
How to save the textbox fields which are dynamically created in the UI using Django?
I'm pretty new to Django. My page contains a text box named 'subtaskName'. onclicking add button, the similar textbox can be created n times with the same text filed name. On Clicking Submit button, I want to retrieve the list of textboxes values (subtaskName []) in Django from the post method. SO that I can iterate them and save them in to Database. After saving, On view page how to dynamically create n textboxes dynamically based on the total record from database. It seems like, this couldn't be done using crispy_forms. On form submit, the values for subTaskName[] are not coming Lets say three textbooks named 'subtaskName' are dynamically added. <input type="text" class="form-control" id="subtaskName"> <input type="text" class="form-control" id="subtaskName"> <input type="text" class="form-control" id="subtaskName"> ====================================================================== Actual code: HTML: <form action="SaveformsTest" method="post"> {% csrf_token %} <!--<div class="form-row"> <div class="form-group col-md-6"> <label style="font-size:40px;" for="projectTitle">Project Title</label> <input type="text" class="form-control" id="projectTitle" placeholder="Project Title"> </div> </div>--> <div class="form-group"> <div class="form-check "> <input class="form-check-input" type="checkbox" id="websiteBuild"> <label class="form-check-label" for="gridCheck"> Build </label> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="websiteUpdate"> <label class="form-check-label" for="gridCheck"> Update </label> </div> <div class="form-group"> <label style="font-size:20px;" for="task1">Website/Content</label> </div> <div class="form-row"> <div class="form-group col-md-2"> <label for="subtaskName">Name</label> <input type="text" class="form-control" id="subtaskName"> </div> <div class="form-group col-md-2"> <label for="subtaskOwner">Owner</label> <select … -
Pass query with url in Django REST Framework
I feel like this should be simple, but what I'm doing isn't paying off. In Django I have this urls.py in my app: from django.urls import path from .views import PostcodessAPIListView, PostcodesAPIID, PostcodesWithinRadius urlpatterns = [ path("<str:postcode>/<int:radius_km>", PostcodesWithinRadius.as_view(), name="results_api_radius"), path("", PostcodessAPIListView.as_view(), name="results_api_list"), path("<int:pk>", PostcodesAPIID.as_view(), name="results_api_detail"), ] And I have this view that should take a postcode and a radius in km, call an external api to convert the postcode to longitude and latitude, and then call the external api again to get postcodes within a certain radius. def get_postcodes_within_radius(self, postcode, radius_km): radius_km = 3 postcodes_within_radius = [] if radius_km <= 20: radius = radius_km * 1000 else: raise ValueError('Radius cannot be over 20km.') GET_LAT_LON_URL = f"{POSTCODE_URL}?" postcode_query = { "query": postcode } postcode_data = requests.get(GET_LAT_LON_URL, headers=None, params=postcode_query).json() print(postcode_data) querystring = { "longitude": postcode_data['result'][0]['longitude'], "latitude": postcode_data['result'][0]['latitude'], "wideSearch": radius, "limit": 100, } res = requests.get(POSTCODE_URL, headers=None, params=querystring).json() for postcode in res['result']: postcodes_within_radius.append(postcode['postcode']) return postcodes_within_radius However, the postcode and radius are not being passed through the url params - what gives? -
Django signal gets triggered before file is saved in server?
I am learning how to work with Django signals and celery tasks. So, I am uploading a bulk csv file to the server and my goal is to read the contents of the file once it is uploaded. Now, this is the approach I used, once the Fileupload object is saved, I am triggering the django post_save signal which basically does some validation and then triggers the celery task (which is where all the file read operations are done). Problem is that file is empty when it gets uploaded to the server. I noticed by commenting out the django signal bit and the file gets uploaded with the proper contents but once I activate the signal, it somehow interrupting with the file upload operation. How can i activate the django signal when the file is completely uploaded with the contents. class FileUpload(models.Model): file = models.FileField(blank=True) type = models.ForeignKey(FileType, on_delete=models.PROTECT, blank=True, null=True) category = models.ForeignKey(FileCategory, on_delete=models.PROTECT, blank=True, null=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=STATUS_NEW) --------- def upload_file(sender,instance,**kwargs): if kwargs['created']: process_upload_file.delay(instance.id) @app.task(ignore_result=True) def process_upload_file(file_id): try: logger.debug('Files:process_upload_file - called.') try: upload_file = FileUpload.objects.get(id=int(file_id)) except FileUpload.DoesNotExist: return None if not upload_file: logger.error('Files:process_upload_file - Could not locate upload file with ID={}'.format(file_id)) return elif not upload_file.type: logger.debug('Files:process_upload_file … -
my Form is passing a NoneType value to my model method calculation, Am I missing instancing something?
I'm trying to pass the input of a Form to my model method, to make some calculation based on my model field database values. I know I can do it with custom tag filters, but that's not effcient as I need to do complex calculation later. I've read somewhere that in Django you cannot pass paramaters to Models, but that sounds to stupid to be true... Am I missing instancing something somewhere ?? There error when I save the new value in the form is np = self.price * value unsupported operand type(s) for *: 'NoneType' and 'int'' so it is related It's also very confusing because if I set a default value inside my method, the calculation is rendering fine in the template. I would really appreciate some help Model class Product(models.Model): sku = models.CharField(max_length=30) price = models.FloatField() def __str__(self): return self.sku def multi(self, value = 2): #THIS DEFAULT '2' IS PROCESSED BY THE METHOD np = self.price * value #AND RENDERS A NP VALUE IN THE TEMPLATE return np View from .models import Product from .forms import Input def index(request): list = Product.objects.all() value = 0 #just to check if request.method == "POST": form = Input(request.POST or None) …