Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Delete column from PostgreSQL (Heroku)
I have a Django project on Heroku, database there - postgresql. So, during manipulation of migrations conflicts with the database arose. When I post a request to the project API, the error occurs IntegrityError at /api/clients/ null value in column "loan_approved" violates not-null constrain But I no longer have this column in my database. As far as I understand, this column was left over from old migrations and I tried to delete it directly: cursor.execute("alter table my_table drop column loan_approved;") then I check all columns in the table as follows cursor.execute("Select * FROM clients_client LIMIT 0") colnames = [desc[0] for desc in cursor.description] But this column is still in the database. Can I delete it in theory? Thanks, any help would be helpful -
Trying to make a visit counter + IP unique in CBV for django blog
I'm doing an integer field in models fou counting the visits, but I would like to be filtered also by IP. counter = models.IntegerField(default=0) class ArticleDetailView(DetailView): model=Post template_name = 'article_details.html' def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) context["cat_menu"]= cat_menu return context def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip I'm not sure how to do the logic in CBV for the count. Any suggestions? -
How to preserve parent ID and filter any further views based on that ID throughout the entire site in Django?
The context: I am working on a site (written in Django) where after selecting a main entity (e.g. a "School" from the list of "Schools") I got a context-independent navbar with fixed link structure (Location, Staff, Students, Financial statements etc.) The idea is that all the views that can be reached trough these links and sub-links are filtered based on the previously selected main entity (school) ID. How I try to solve the task: I save the School ID as a session variable upon selection, and access this variable in every single view that follows through request.session. The pain The pain is that I can't really use generic views (Generic detail view must be called with either an object pk or a slug - the error message says) and I have to write views manually, overriding the get() function of the class Based views or using function views like that: def LocationDetails(request): context = {} my_school_pk = request.session['active_school'] my_location = Location.objects.get(school=my_school_pk) context['location'] = my_location return render(request, 'location/location_details.html', context=context) The question: Do you know please a better, more concise, more elegant way for solving this issue? Thank you in advance! -
How to make google, facebook authentication in django with flutter
I am using Flutter for a mobile app and django for backend API. I want user to be able to login with accounts from Facebook, Google etc. How Can I implement this? Also I saw that dj-rest-auth provides requests for Social Media Authentication. Should I use something like this? -
Getting permission denied when I `python manage.py runserver` locally
I am running a Django app locally and I cant seem to understand why I am getting this error when I runserver. I am in a virtualenv and so I don't see why it is grabbing from outside. [ERROR 2020-10-21 19:00:36,868] base.py [:256] handle_uncaught_exception: Internal Server Error: /favicon.ico Traceback (most recent call last): File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/handlers/base.py", line 108, in get_response response = middleware_method(request) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/middleware/common.py", line 74, in process_request if (not urlresolvers.is_valid_path(request.path_info, urlconf) and File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 647, in is_valid_path resolve(path, urlconf) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 522, in resolve return get_resolver(urlconf).resolve(path) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 366, in resolve for pattern in self.url_patterns: File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 402, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/core/urlresolvers.py", line 396, in urlconf_module self._urlconf_module = import_module(self.urlconf_name) File "/opt/anaconda3/envs/py2/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/andynguyen/Documents/AggrigatorCode/aggrigator/site_aggrigator/urls.py", line 5, in <module> url(r'', include('accounts.urls')), File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 33, in include urlconf_module = import_module(urlconf_module) File "/opt/anaconda3/envs/py2/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/andynguyen/Documents/AggrigatorCode/aggrigator/accounts/urls.py", line 1, in <module> from accounts import views File "/Users/andynguyen/Documents/AggrigatorCode/aggrigator/accounts/views.py", line 27, in <module> import geonameszip File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/geonameszip/__init__.py", line 21, in <module> os.makedirs(BASE_DIR) File "/opt/anaconda3/envs/py2/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/var/lib/geonameszip/' -
Python Django , Couldn't import Django?
I have been learning django 3.x and I set up all necessary staff. I activated my virtual enviroment and it works, but when I try to run this command it gives me this error: Traceback (most recent call last): File "C:\Users\dzhiv\Dev\django-bootcamp\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\dzhiv\Dev\django-bootcamp\manage.py", line 22, in <module> main() File "C:\Users\dzhiv\Dev\django-bootcamp\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have python on path enviroment.(If I had not, cmd would not show me when I type python) I created virtual envrioment(python -m venv . ) I started django project(django-admin startproject ...) I activate virtual enviroment with (.\Scripts\activate) and it works. When I run this (python manage.py createsuperuser) command I get errors. So I am on a windows 10 pc and I used powershell or VsCode's terminal(same, I know). What should I do ? -
How to curl a date for Django Rest Framework?
My model has: class Player(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) date_of_birth = models.DateField() I am trying to send a curl like this: curl -X POST -H "Content-type: application/json" -d '{ ..., "date_of_birth":"1991-01-02"}' http://localhost:8000/api/player/ however, I get: django.db.utils.IntegrityError: null value in column "date_of_birth" violates not-null constraint DETAIL: Failing row contains (4, null, 24). I tried -
Scrapyrt not using callback functions
these are my files: views.py from uuid import uuid4 from urllib.parse import urlparse from django.core.validators import URLValidator from rest_framework.decorators import api_view, renderer_classes from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from time import sleep import os import json import requests def is_valid_url(url): validate = URLValidator() try: validate(url) # check if url format is valid except ValidationError: return False return True @csrf_exempt @api_view(['POST',]) def getProduct(request): url = request.POST['url'] if not url: return JsonResponse({'error': 'Missing args'}) if not is_valid_url(url): return JsonResponse({'error': 'URL is invalid'}) data = { "request": { "url": str(url), "callback": "start_requests", "dont_filter": "false" }, "spider_name": "GetinfoSpider" } scrapyrt = 'http://127.0.0.1:9081/crawl.json' try: #print(str(requests.post(scrapyrt, data = data))) r = requests.post(scrapyrt, json = data) print(r) return JsonResponse({'data': r}) except Exception as e: print(e) return JsonResponse({'error': str(e)}) this is my spider file getInfo.py import scrapy from scrapy_splash import SplashRequest from ..items import WallmartItem import logging class GetinfoSpider(scrapy.Spider): name:str = 'GetinfoSpider' allowed_domains = ['www.walmart.com'] script1:str = ''' function main(splash, args) splash.private_mode_enabled = false url = args.url assert(splash:go(url)) assert(splash:wait(1)) splash:set_viewport_full() return splash:html() end ''' def start_requests(self, url): yield scrapy.Request(str(url), callback=self.parse_item, meta={ 'splash': { 'args': { # set rendering arguments here 'lua_source': self.script1 }, # optional parameters 'endpoint': 'render.html', # optional; default is render.json } }) def … -
django widget_tweaks supports select tag?
Can I make something like this? {% for field in selected_products_form %} <div class="mt-2"> {% render_field field type="select" class="selectpicker" name="food" data-style="btn-primary" data-width="auto" multiple="true" data-selected-text-format="count > 2" data-live-search="true" data-actions-box="true"%} </div> <!-- HERE I WANT TO MAKE OPTIONS IN 'FOR' LOOP (THERE WILL BE A LOT OF THEM) --> {% endfor %} The problem is: tag closed after render and my 'for' loop is outside tag. Maybe I can pass my loop inside render ... But that render adding attrs inside tags, not tags that have to be inside... btw, form fields is MultipleChoiceFields. -
Django Stripe PaymentIntent
I am trying to setup the paymentIntent API from Stripe but I can't seem to figure out the error I am getting. I followed along from this video: https://www.youtube.com/watch?v=w1oLdAPyuok&t=1414s I have a react frontend which makes a request to my Django view: try { const { data: clientSecret } = await axios.post("http://127.0.0.1:8000/paymentIntent/", { amount: price * 100 }); My view: from django.shortcuts import render from django.http import HttpResponse from django.views.generic import View from django.views.decorators.csrf import csrf_exempt import logging from rest_framework.views import APIView from rest_framework import status, generics from rest_framework.response import Response from rest_framework.decorators import api_view from django.conf import settings import stripe stripe.api_key = "pk_test_51HWMwZB5hTmoPZOBJd00GjCvDYUg" @api_view(['POST']) def payment(request): try: amount = request.body paymentIntent = stripe.PaymentIntent.create( amount = amount, currency = "usd", # payment_method_types=['card'], # capture_method='manual', metadata={'integration_check': 'accept_a_payment'}, ) data = paymentIntent.client_secret return Response(data,status=status.HTTP_200_OK) except : return Response(status=status.HTTP_400_BAD_REQUEST) -
Querying ManyToManyTable In Django
Given the following model, I'm trying to generate a data set that will get the quantity field from OrderItems while also getting the other columns from Item and Order. I'm trying to write the query in Django's ORM but have been having issues. class Order(models.Model): items = models.ManyToManyField("Item", through="OrderItems") order_date = models.DateTimeField() class Item(models.Model): name = models.CharField(max_length=250) orders = models.ManyToManyField("Order", through="OrderItems") class OrderItems(models.Model): order = models.ForeignKey("Order", null=False, on_delete=models.CASCADE) item = models.ForeignKey("Item", null=False, on_delete=models.CASCADE) quantity = models.IntegerField() The query I've tried: Order.objects.prefetch_related('items').filter(id=order_id) That will get me the Items for the order, but I can't figure out how to get the quantity field. -
template does not exists not work even all thing correct
i dont know where is my mistake that am sure my code is correct view.py: from django.http import HttpResponse from .models import Task from django.template import loader from django.template.response import TemplateResponse def index(request): list_task = Task.objects.all() template = loader.get_template('new2/index.html') context = { 'list_task': list_task } return HttpResponse(template.render(request, context)) models.py from django.db import models class Task(models.Model): Name_task = models.CharField(max_length=200) Age_task = models.CharField(max_length=200) index.html: {% if list_task %} <ul> {% for i in list_task %} <li> <a href="#">{{i.Name_task}}</a> </li> {% endfor %} </ul> {% else %} {% endif %} urls.py: from django.contrib import admin from django.urls import path from new2 import views urlpatterns = ( # path('admin/', admin.site.urls), path('', views.index, name='index'), i tried this code in setting.py: 'DIRS': [os.path.join(BASE_DIR, 'todoapp')], and this also for template location but still not works : 'DIRS': [r'C:\Users\hajar\Downloads\new\new1\new2\template'], the path for tamplate was: C:\Users\hajar\Downloads\new\new1\new2\template\new2\index.html any one can give me the solution 3 days actualy i tried with nothing error : context must be a dict rather than WSGIRequest. and template not exist thank you -
How can I write an AWS lambda function for python to resize images?
I am looking for a python script for AWS lambda function but I can't seem to find a proper one. I have looked online and haven't found any answers(yet) to completely fulfill my requirements. I want my photos to be resized immediately and then uploaded into the bucket. I have seen many already build scripts but I wondered how to write that script on the lambda's function on my own. I want to resize my images on different sizes depending on the folder they are being uploaded to. (for example folder1 images to be resized at 600x400 and folder2 at 500x500) Is anyone able to help me with this? I'm very new to this whole AWS services and it's bugging me. -
Django: problem with assignment of the ForeignKey
I want to update the database records from the Pandas DataFrame, and I faced an issue with the ForeignKey. for i, r in df.iterrows(): try: person = Person.obejcts.get(id_no=r['ID Number']) except Person.DoesNotExist: print(f"{r['ID Number']} does not exist in the database") continue t = Task.objects.get_or_create(no=r['Task_no'], defaults={'area': r['Area']}) if not t[1]: t[0].area = r['Area'] t[0].person = person t[0].save() I got an error saying "Task.person" must be a "Person" instance. Any idea what I'm doing wrong? -
remove comments of minified css/js in django compressor
I have django-compressor in my project and i use this filters for minify: 'css': [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter' ], 'js': [ 'compressor.filters.jsmin.JSMinFilter' ] that works correctly. but this not removed license comments like: /*! * example plugin v1.1.9 * * Copyright 2015-present me * Released under the MIT license * * Date: 2020-09-10 13:16:21 */ i searched and i found that cssmin filter has arguments that removed them. but i think django-compressor not supported it. also i think that i can with COMPRESS_PRECOMPILER config remove this comments. -
How to use hyperlinkedModelSerializer in django rest framework
class ProgramSerializer(serializers.ModelSerializer): class Meta: model = Program fields = '__all__' class ProgramMiniSerializer(serializers.ModelSerializer): programCode = serializers.HyperlinkedRelatedField(many=True,view_name='program-detail', read_only=True) class Meta: model = Program fields = ('programCode', 'pro_name', 'url', 'DepartmentID') -
Django ForeignKey Relationship with an intermediate Table
I have the Goal Model and every Goal can have one Mastergoal and or multiple Subgoals. Goals are connected with Links and every Link can have a different weight. How do I achieve this with Django? What I've got so far: class Goal(models.Model): user = models.ForeignKey(CustomUser, related_name='goals', on_delete=models.CASCADE) name = models.CharField(max_length=300) sub_goals = models.ManyToManyField(to='self', through='Link', symmetrical=False, related_name='master_goals') class Link(models.Model): master_goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name="sub_links") sub_goal = models.OneToOneField(Goal, on_delete=models.CASCADE, related_name="master_links") weight = models.PositiveSmallIntegerField(default=1) I can't just add an ForeignKey Field on Goal to itself, because every Link can have a different weight. The solution I've got now works, but it feels wrong. I want to be able to access a Goal's Mastergoal like this: goal.master_goal -
Django framework project
I have tried to make a blog using python django and I have created it but while I try to register and save the data it says operationalError no such table: main_auth_user__old I have tried python manage.py migrate still I am having problems. -
See if values is related to ManyToManyField
I have two models, Major and Course like this: class Major(models.Model): required_courses = models.ManyToManyField(Course, related_name='required_courses') class Course(models.Model): # a bunch of fields... I have several Majors (Computer Science, Psychology, etc.) where each of them contains a different set of required_courses. In my views.py I am getting the course like this course = Course.objects.get(id=pk). Is there an elegant way to see if this particular class is in required_courses in any of my Major models? Im trying to use majors = Major.objects.all().values("required_courses") but that just returns <QuerySet [{'required_courses': 1}, {'required_courses': 2}, {'required_courses': 4}, {'required_courses': 5}]> -
ERRORS: products.ProductsEnterprise: (fields.E180) SQLite does not support JSONFields
after doing migrate in django i get this error. ERRORS: products.ProductsEnterprise: (fields.E180) SQLite does not support JSONFields. -
accsec dicts inside one list python
i have this dicts inside list : myList = [ { 'foo':12, 'bar':14 }, { 'foo':52, 'bar':641 }, { 'foo':6, 'bar':84 }] print(myList) = [{'foo': 12, 'bar': 14}, {'foo': 52, 'bar': 641}, {'foo': 6, 'bar': 84}] i want to access to all dict with key 'foo' only to get this ruslut : [{'foo': 12}, {'foo': 52}, {'foo': 6}] or [12, 52, 6] i try print(myList['foo']) but i got erorr -
Django LDAP: uid and password set from post request
I am a beginner in Django and I am trying through LDAP at login to set uid and password from POST request but I can`t figure it out. Im using django rest framwork which returns token after login superuser but I dont know how to do it with LDAP Is there a way to do it? Here is my code: setings.py AUTH_LDAP_SERVER_URI = "ldap://exmaple.com" # I need something like this but I dont know how to do it user_from_POST_request = request.GET.get('username') password_from_POST_request = request.GET.get('password') AUTH_LDAP_BIND_DN = "uid" + user_from_POST_request + ",ou=group,dc=exmaple,dc=com" AUTH_LDAP_BIND_PASSWORD = password_from_POST_request AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=group,dc=exmaple,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)" ) AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) urls.py path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'), request http://127.0.0.1:8000/api-token-auth/ body: username: user_login password: password -
Factory-Boy - KeyError: 'locale'
Got an exception: def generate(self, params): > locale = params.pop('locale') E KeyError: 'locale' Code example: import factory from django.db import models class MyModel(models.Model): name = models.CharField(max_length=100) price = models.PositiveIntegerField() is_cheat = models.BooleanField() class MyModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel name = factory.Faker("name") is_cheap = factory.Faker("boolean") price = factory.Maybe("is_cheap", yes_declaration=factoryFaker("pyint", max_value=10), no_declaration=factory.Faker("pyint", min_value=100)) How to solve that issue? Everything worked few days ago. -
I can't get my tags value from object Django
I am trying to get my BlogPost's tags value from obj in my case but I am not sure how. I am not sure but I think there is a different approach because for my tags field I used : manytomanyfield. For my other fields it is properly working. My models.py class Tag(models.Model): tag = models.CharField(max_length=250) def __str__(self): return self.tag class BlogPost(models.Model): # blogpost_set -> queryset .... title = models.CharField(max_length=120) content = models.TextField(null=True, blank=True) tags = models.ManyToManyField(Tag) .... This is a part of my views.py @login_required(login_url='login') def blog_post_update_view(request, slug): template_name = 'form.html' update_view = True obj = get_object_or_404(BlogPost, slug=slug) form = BlogPostForm(some_title=obj.title, some_content=obj.content) category = Category.objects.all() tagss = Tag.objects.all() print(obj.title) print(obj.tags) .... This is the value of obj.tags in cmd: I do have tags in my BlogPost -
Django annotate date with timedelta and increase
I am trying to query all the expired bookings and i don't have any fields like end_date, I have start date and total days. This is my query: import datetime from django.db.models import Avg, Count, Min, Sum, FloatField, ExpressionWrapper, F, DateTimeField trip = Booking.objects.annotate( end_date=ExpressionWrapper( F('start_date') + datetime.timedelta(days=F('itineraray__days')), output_field=DateTimeField() ) ) these are my models: class Itinerary(models.Model): days = models.PositiveSmallIntegerField(_("Days"), null=True, blank=True) class Booking(models.Model): itinerary = models.ForeignKey( Itinerary, on_delete=models.CASCADE ) start_date = models.DateField(_("Start Date"), null=True, blank=True) def get_end_date(self): return self.start_date + datetime.timedelta(days=self.itinerary.days) You may be noticed that I have a method to get end_date def get_end_date(self): That is why I am trying to annotate to get the end date and query based on the end date to get expired booking. in my query, you may noticed this line: DateTime.timedelta(days=F('itineraray__days')) so you know timedelta days take argument type as an integer but passed this itineraray__days which caused the error. Can anyone help me in this case?