Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Incrementing a variable of a class based on initiation of another class python/django
My goal is to display the total number of entries in a specific contest. Initially I tried doing this within the template section by incrementing a counter for each contest as I looped through entries. My thought is that when an entry submission is created, the total_submissions for the corresponding contest should be incremented, however I'm not sure how to do it. Model: class Contest(models.Model): contest_name = models.CharField(max_length=200) contest_description = models.CharField(max_length=5000) contest_start_date = models.DateTimeField('start date') contest_end_date = models.DateTimeField('end date') submission_count = models.IntegerField(default=0) def __str__(self): return self.contest_name class Submission(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) date_uploaded = models.DateTimeField(auto_now_add=True) votes = models.IntegerField(default=0) def __init__(self): #increment the submission_count variable for the corresponding contest Other attempt by using templates: <h1>Current Contests</h1> <div class="row"> {% if current_contest_list %} {% for contest in current_contest_list %} <div class="col-sm-4"><h1><a href="{% url 'contests:detail' contest.id%}">{{ contest.contest_name }}</a></h1> <img src="media/{{contest.display_image}}" class="img-responsive" alt="image"> {{ contest.contest_name }} {% for submission in submission_list %} {% if submission.contest == contest.contest_name %} <P>Hi!</P> {% endif %} <p>{{ submission.contest }} {{ contest.contest_name }}</p> {% if submission.contest == contest.contest_name %} <P>Hi!</P> {{ forloop.counter }} {% set total_submissions = forloop.counter %} {% endif %} {% endfor %} <p>Total entries: {{total_submissions}} </p> When I did this, … -
Builtins error when scrapy is called - Django
I´m using Django - scrapy to create an app for crawl some sites. This is my views.py on Django it catches the POST values and run the scrapy when crawlit() is called from django.shortcuts import render from django.http import HttpResponse as hres from .MetaCrawl import InitCrawl import json def index( req ): return render( req, 'crawler/index.html' ) def crawlit( req ): val = req.POST['value'] #https://stackoverflow.com InitCrawler( val ) return hres( json.dumps({'message':'Sent!'}) ) At the same view.py level I have a file called MetaCrawl.py import scrapy from twisted.internet import reactor from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging class Spider( scrapy.Spider ): name="project" links = [] start_urls = links def __init__( self, l ): self.links.append( l ) def parse( self, response ): for item in response.xpath('//a'): print(item) class InitCrawl: def __init__( self, link ): configure_logging() crawler = CrawlerRunner() crawler.crawl( Spider ) d = crawler.join() d.addBoth( lambda _: reactor.stop() ) reactor.run() I got this error: builtins.ValueError: signal only works in main thread and sometimes I got this error: ValueError: signal only works in main thread I followed this tutorial Scrapy Spiders and I´m lost. How could I solve this? -
Conditional empty field validation on Django admin
I have a form on my admin that have a choice field with an option Other, and a CharField where the user should describe the contentes of the option. I am trying to override the clean method to not allow the form to be send in case the user select Other and left the field empty. What I have tried so far: def clean(self): if self.cleaned_data.get('option') == 'Other' and self.cleaned_data.get('Other') is none: raise ValidationError('You must describe your selection') def clean(self): if self.cleaned_data.get('option') == 'Other' and self.cleaned_data.get('Other') = "": raise ValidationError('You must describe your selection') def clean(self): if self.cleaned_data.get('option') == 'Other' and self.cleaned_data.get('Other', '').strip('') == '': raise ValidationError('You must describe your selection') None of these worked. Any hint? -
How to display (hierarchical) object members in django admin
I am using django 2.0.8 with Python 3.5 and django-threadedcomments for commenting functionality. Here are some of my models: foo/models.py from django.db import models from django.contrib.contenttypes.fields import GenericRelation from threadedcomments.models import ThreadedComment from django.conf import settings class AbuseReport(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False, default=1, on_delete = models.CASCADE) class Like(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False, default=1, on_delete = models.CASCADE) class Likeable(models.Model): likes = GenericRelation(Like) class Meta: abstract = True class ThumbVote(models.Model): VOTE_TYPES = ( ('U', 'Upvote'), ('D', 'Downvote'), ) owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False, default=1, on_delete = models.CASCADE) vote = models.CharField(max_length=1, choices=VOTE_TYPES) class Reportable(models.Model): abuse_report_count = GenericRelation(AbuseReport) class Meta: abstract = True class ThumbvoteableReportableComment(ThreadedComment): thumbvotes = GenericRelation(ThumbVote) abuse_report_count = models.PositiveIntegerField(default=0,blank=False,null=False) foobar/models.py from foo.models import ThumbvoteableReportableComment # Create your models here. class Post(Likeable, Reportable): pass class PostComments(ThumbvoteableReportableComment): post = models.ForeignKey(Post, related_name='comments', on_delete = models.CASCADE) foobar/admin.py from django.contrib import admin from .models import Post, PostComments class PostCommentsInline(admin.TabularInline): model = PostComments readonly_fields = ('thumbvotes',) fields = ('comment', 'abuse_report_count') class PostAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} list_display = ('title', 'pub_date') inlines = [PostFileInline, PostPictureGalleryInline, PostCommentsInline] def save_model(self, request, obj, form, change): obj.author = request.user obj.save() # Register your models here. admin.site.register(Post, PostAdmin) When I go to the django admin page, there are the following problems: The … -
Django Queryset crash when string in integerfields
I have a search screen where the parameters are entered and filtered using a queryset. I have an integerfield and if the user enters in alpha characters in it, it will crash when I perform a queryset.filter because there's alpha in an integer. Is there a way to get django to simply discard this rather than raising an exception? Thank you. -
Is it right to run crontab service and wsgi within a single docker container
Currently, I have a Django wsgi to handle web traffic. Now, I would like to start a crobtab service, to run periodic background job. This is what I had done django\Dockerfile FROM python:3.6.4-alpine3.4 ... RUN chmod +x entrypoint.sh ENTRYPOINT ["sh", "entrypoint.sh"] CMD /usr/local/bin/gunicorn web.wsgi:application -b django:5000 --log-level=info --error-logfile=/var/log/gunicorn3.err.log django\entrypoint.sh #!/bin/sh ... python manage.py crontab add # https://stackoverflow.com/questions/37015624/how-to-run-a-cron-job-inside-a-docker-container # # "crond -help" yields: # # -f Foreground # -b Background (default) # -S Log to syslog (default) # -l N Set log level. Most verbose:0, default:8 # -d N Set log level, log to stderr # -L FILE Log to FILE # -c DIR Cron dir. Default:/var/spool/cron/crontabs # start cron /usr/sbin/crond -f -l 8 exec "$@" docker-compose.yml django: build: context: ./django dockerfile: Dockerfile restart: always depends_on: - pgbouncer expose: - "5000" volumes: - static_data:/app/static If I use the above setup, I notice that. My schedule cron worker is running periodically. But, wsgi unable to serve web traffic. First, I try to change in django\entrypoint.sh # start cron /usr/sbin/crond -f -l 8 to # start cron /usr/sbin/crond -b -l 8 After making above change, My schedule cron worker is no longer running. Not sure why. wsgi can serve web traffic. May I … -
Django forms field not required asterix still there when shouldnt
I have a ModelForm with two fields that shouldnt be required. One of them is defined with a null=True and a blank=True. The other one is a checkbox with a widget required=False My model user_id = models.CharField('Genium360 member #', max_length=300, null=True, blank=True) My form class MyForm(ModelForm): class Meta: model = ... fields = ... widgets = { 'communications': CheckboxInput(attrs={'required': 'false'}), } My template <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Soumettre"/> </form> I can send the for form without filling these two fields, but the required asterix (*) still show in the form. How can I remove it. I'm lost on why it still show. Thanks. -
Webpack prod config vs dev config issues
I'll be brief.. I am trying to reuse one webapp that's been open sourced a while ago that was written using some Django and react js... Now I am a devops engineer so my skillset when it comes to JS and even django are fairly limited so I am stuck .. My main problem is that this webapp can run just fine locally.. so I can start it and connect using http://localhost:8000 , but whenever I try and set it up on a server and make it "public" for the internal network it fails with accessing all the JS assets. I know the problem comes with my webpack configs but I can't sort it out.. Been trying all day but I can't even find the proper documentation since its using webpack 2.5 https://github.com/tsprasath/estate/tree/master/webpack I am attaching the link to the webpack configs from the repo.. If anyone can at least point me to the right thing to look at, that would be helpful. Thanks in advance! -
Django: ImproperlyConfigured The SECRET_KEY setting must not be empty when executing gunicorn
I'm trying to deploy a django application on AWS. I've read all the existing posts regarding the same issue and include the os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango_with_django.settings") in manage.py and wsgi.py but still it does not work. My project structure is the following one: --chimpy -botApp -settings -base.py -production.py -wsgi.py -manage.py These are my files: -base.py: """ Django settings for botApp project. Generated by 'django-admin startproject' using Django 2.0.5. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ 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.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'whatever' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] LOCALE_PATHS = [ os.path.join(BASE_DIR, '../../locale'), ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profiles', 'portfolios', 'django_extensions', 'rest_framework', 'corsheaders', ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'botApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '../../templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
python-decouple and SECURE_PROXY_SSL_HEADER in Django
For my Django application I use python-decouple. Now in my settings I'd like to use it for SECURE_PROXY_SSL_HEADER. My idea was this: # https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = config('SECURE_PROXY_SSL_HEADER', default=None, cast=Csv(post_process=tuple)) However, my problem is the following: When I do not set it, the default value is None. Unfortunately, it seems like it conflicts with the cast. Here in Python REPL: >>> SECURE_PROXY_SSL_HEADER = config('SECURE_PROXY_SSL_HEADER', default=None, cast=Csv(post_process=tuple)) ▌ As you can see, it does not return. Am I doing something wrong or what should I do? -
TypeError: perform_create() takes 1 positional argument but 2 were given
I am using Django Rest Framework here. When I make a post request from the front end with React, the title error is returned. My perform_create() function is within my view class: class MaxListCreate(generics.ListCreateAPIView): queryset = Max.objects.all() serializer_class = MaxSerializer filter_backends = (filters.OrderingFilter,) ordering_fields = ('exercise', 'date',) ordering = ('exercise', 'date',) permission_classes = (permissions.IsAuthenticated,) def perform_create(self): user = self.request.user serializer.save(user=user) # User can only access the data associated with the user. def get_queryset(self): user = self.request.user return Max.objects.filter(user=user) The endpoint data format should be: { "id": 5, "date": "2018-08-07", "max_lift": 80, "user": 1, "exercise": 1 }, and the form sends: {"exercise":"3","date":"2018-08-23","max_lift":"70"} The intention of the perform_create() function is to supply the user key from the back end. Any help would be appreciated, -
django admin changes not reflecting on pythonanywhere free server
I have created an app "mybook" using django 1.11 and python 3.6 on pythonanywhere.com free server. Url of app is http://suryavsics07.pythonanywhere.com/, issue is that none of changes are reflecting on admin. I have created customermodel Directory structure is as bellow: moneybook media/ moneybook/ __init__.py __init__.pyc settings.py settings.pyc urls.py urls.pyc wsgi.py mymoney/ __init__.py admin.py apps.py models.py tests.py urls.py views.py static/ db.sqlite3 manage.py I run python3 manage.py check and 0 error found. Where i am wrong? Code in model.py file: from django.db import models # Create your models here. class Customer(models.Model): cust_id = models.IntegerField("Customer Id",unique=True,db_index=True) cust_name = models.CharField("Name",max_length=200,null=True) cust_email = models.EmailField("Email Id",max_length=200,unique=True,default='NULL',null=True,) cust_mobile = models.CharField( "Mobile No.",max_length=15,null=True) cust_pin = models.IntegerField("PIN",blank=True) cust_created_date = models.DateField("Registration Date",auto_now=True) def __str__(self): """String for representing the Model object.""" return self.cust_name -
ImportError: No module named web3 DJANGO
Im trying to set up a wallet on Django, but i keep getting this error: ImportError: No module named web3 this is how i from web3 import Web3 (also tried import web3) -
django inspectdb utf8mb4 error
Python manage.py inspectdb is giving following error even after all tables are having CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci from django.db import models Unable to inspect table 'execution' The error was: (3719, "3719: 'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous.", None) -
ListView ordered by user and date
I have this view: class IndexLatest(ListView): context_object_name = 'latest' model = models.MyModel template_name = 'my_app/index.html' def get_queryset(self): return MyModel.objects.filter(user_id=self.request.user,) How can I add the order_by argument to the queryset? The model has a date field, and I've tried to add it after the comma but it did not worked out! Thanks for your help! -
DRF Object level permissions check for single field
How do you add permissions to a model so that any user can add a new instance, but only a logged in user can add a particular attribute? Django models.py: class Ingredient(models.Model): name = models.CharField(max_length=100, unique=True) recipes = models.ManyToManyField(Recipe, related_name='ingredients', blank=True) DRF views.py: class IngredientViewSet(viewsets.ModelViewSet): queryset = Ingredient.objects.all() serializer_class = IngredientSerializer permission_classes = (IsUserForRecipeOrBasicAddReadOnly,) DRF permissions.py: class IsUserForRecipeOrBasicAddReadOnly(permissions.BasePermission): """ Custom permission to only allow logged in users to add an ingredient AND associate its recipe(s). """ message = 'You must be logged in to add an Ingredient to a Recipe.' # using this method so I can access the model obj itself def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, if request.method in permissions.SAFE_METHODS: return True # Check if we are creating, and if the recipes are included, and if they are not a user. If so, return False if request.method == 'POST' and obj.recipes.all().count() > 0 and request.user.is_anonymous: return False else: return True I see the appropriate calls/prints to the custom permission class, but I can still make a PUT request with a list of recipe id's and it does not error with the message. Notes - I am getting two PUT requests, both … -
call a python script from ElasticSearch daily
I have logstash scheduled to read data from database every day at 3:00 A.M.. What I want to do is whenever the index is read I want to call a Python Function defined in my Django Project that will process index and then update another index in ElasticSearch. Basically, I am fetching all transactions done daily via logstash and then want to run python script, if fetch was successful then process transactions (apply some machine learning stuff) and save result as another index in Elasticsearch so I want help with: Call a python script from Elasticsearch when index is updated -
Django admin site redirecting to wrong location
I have a Django app, being deployed to Amazon Lambda using zappa. The admin routes are registered under /api, and when deployed, they get further deployed to /int, so the admin site is available under /int/api/admin/. However, this site is served from CloudFront, which takes requests to /api and proxies them to /int/api. When I hit /api/admin/ on CloudFront, it requests /int/api/admin/ from my Lambda instance, and that sends a redirect to /int/api/admin/login which fails. How do I fix this? -
Django extract string from [ErrorDetail(string='Test Message', code='invalid')]
I would like to show in my template only message that is in string variable, but I don't know how. I am using Django Rest Framework. My code: form.html <p>{{ serializer.amount.errors }}</p> serializers.py from rest_framework import serializers from .models import Data, Material class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('order_date', 'material', 'amount', 'delivery_number', 'employee') read_only_fields = ('id', 'insert_time') extra_kwargs = {"amount": {"error_messages": {"invalid": "Test Message"}}} views.py class Form(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'zulieferung/form.html' def get(self, request): materials = Material.objects.distinct('material_unit_id') return Response({'all_materials': materials}) def post(self, request): materials = Material.objects.all() serializer = DataSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'all_materials': materials}, status=status.HTTP_201_CREATED) return Response({'serializer': serializer}, status=status.HTTP_400_BAD_REQUEST) And instead of Test Message in my template I have [ErrorDetail(string='Test Message', code='invalid')] -
Add FormMixin to DetailView in Django
I would like to add a form to a generic Detail view. Official documentation says that's a bad idea and basically suggests this: from django import forms from django.views.generic import DetailView from books.models import Author class AuthorInterestForm(forms.Form): message = forms.CharField() class AuthorDisplay(DetailView): model = Author def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AuthorInterestForm() return context and: from django.http import HttpResponseForbidden from django.urls import reverse from django.views.generic import FormView from django.views.generic.detail import SingleObjectMixin class AuthorInterest(SingleObjectMixin, FormView): template_name = 'books/author_detail.html' form_class = AuthorInterestForm model = Author def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('author-detail', kwargs={'pk': self.object.pk}) Simply said, in order to avoid conflicts between same-named functions that do different things, it's best practice to split form and display part into two. Which is fine. However I don't get how am I supposed to call the appropriate view? From the sort-of selection view below? How do I define this in urls? The whole idea was to have a single template which would receive object in the context AND a unrelated from -> which should uppon submission return POST to the same view. If I have to select get() or … -
How to nest two serializers with same model
I have two serializers with same model. I want to nest them. Unfortunately this approach does not work: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['name', 'word_count'] class BetterBookSerializer(serializers.ModelSerializer): book = BookSerializer(many=False) class Meta: model = Book fields = ('id', 'book') Expected result: { "id": 123, "book": { "name": "book_name", "word_count": 123 } } -
Code: unknown, Error: LinkedIn encountered an internal error while logging in. How to obtain error message returned by LinkedIn API
I am using Django Allauth with Django 2.0.8 and 3.5 I have followed the instructions for using LinkedIn to login to a site. However, when I attempt to login to my website, I am getting the following message: Social Network Login Failure An error occurred while attempting to login via your social network account. There is no log output containing more information - which makes debugging this unnecessarily difficult. Based on an answer for this question, I have added information to my template which sheds some more light: Code: {{ auth_error.code }}, Error: {{ auth_error.exception }} However, the error message is: Code: unknown, Error: LinkedIn encountered an internal error while logging in. Please try again. Which doesn't help very much. I want to see the actual response returned by the LinkedIn API, so I can get to the bottom of the problem. I searched through the code and found where the error was being raised: /path/to/allauth/socialaccount/providers/base.py#L66 The error is raised when the extract_id() method is called. The implementation of that function in LinkedInOAuth2Provider expects an 'id' key in the passed argument, however, only the passed argument only contains the email address in the dictionary. Why is the LinkedIn API not … -
'endblock', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
I am trying to render three columns for per row in my html file by using Django2.1 and Bootstrap4. The piece of HTML code looks like following: <main class="container" role="main"> {% for treasure in treasures %} {% block row %} <div class="col-sm-4 py-2"> <div class="card card-body h-100"> <h4 class="card-title">{{ treasure.name }} </h4> <img class="card-img-bottom mw-100 mh-100" src="{{ treasure.img_url }}" alt="A Kind of Treasure"> </div> </div> {% if forloop.counter|divisibleby:3 %} {% endblock %} {% block row %} {% endif %} {% endblock %} {% endfor %} </main> The error I get is: Invalid block tag on line 44: 'endblock', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? -
Boto s3 permission issue
I've come across very weird permission issue. I'm trying to upload a file to s3, here's my function def UploadFile(FileName, S3FileName): session = boto3.session.Session() s3 = session.resource('s3') s3.meta.client.upload_file(FileName, "MyBucketName", S3FileName) I did configure aws-cli on the server. This function works fine when I log into server and launch python interpreter but fails when called from my django rest api with: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied No idea why the same function works when called from interpreter and fails when called from django. Both are in the same virtual environment. Any suggestions? -
Cannot update svg file(s) for saleor framework + python + django
I would like to know how should i could manage to change the static files use by the saelor framework. I've tried to change the logo.svg but failed to do so. I'm still learning python program while using the saleor framework for e-commerce. Thank you.