Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Impossible to scrape this website anymore
I am currently realising a project for school (torrents stream website like netflix) with Python/Django/NodeJS. Since the begin of project, i am scrapping the IMDb website to get data about movies (synopsis, casting, rate etc.). It worked well. Then, since few days I just can't scrape anymore. My request returns me an Error 503. At first, I thought about IP ban, but when i'm trying to scrap with Curl, it works fine. Actually I'm asking myself if the problem doesn't come from IMDb's robots.txt file ? How to be sure ? If it's the case, there are a way to bypass this ? Do you know any alternative ? Thanks for your help. Bye :) -
Display django chartit x-axis in right order with PivotDataPool
When I use Chartit PivotDataPool the month number is not in the right order. Chartit PivotDataPool graph is in this order 1, 10, 11, 2, 3, 4, 5, 7, 8, 9. I want to have right order like 1, 2, 3, 4 , 5, 6, 7, 8, 9, 10, 11. ![Graph image][1] ![1]:(https://imgur.com/UPBZY8G) ds = \ PivotDataPool( series= [{'options': { 'source': DerangementAdsl.objects.filter(annee=year), 'order_by': ['mois'], 'categories' : ['mois'], 'legend_by': ['sous_traitant'], }, 'terms': { 'total': Count('id') } } ]) pivcht = PivotChart( datasource=ds, series_options=[{ 'options': { 'type': 'column', 'stacking': True, 'order_by': 'mois', }, 'terms': ['total'] }], chart_options={ 'title': { 'text': 'Répartition dérangements relevés / structure' }, 'xAxis': { 'title': { 'text': 'Semaine' } } } ) -
Django createsuperuser function: no error but not working
I was trying to create a superuser a while back in Django, but I encountered a problem while doing so. Django won't create a superuser on its own but nor did it return a problem, leaving me no clue of what is going on in the backend. Screenshots: image 1: superuser's names are unique, but Django ignored it image 2: nothing was written into the database Settings.py: """ Django settings for pymun project. Generated by 'django-admin startproject' using Django 3.0b1. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/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/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '%m9@%@uhw99kbpfubd8um1svt&t2dp$daden_favr0o((&ng6_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', 'core.apps.CoreConfig', '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 = 'pymun.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Unable to mailmerge into a template word document when launched on heroku
I am working on a django application in which users input is inserted into a template word document. I used the mailmerge library to achieve this. It was all working fine on my local server but when I deployed the app to heroku it started giving me errors. The error I get on the heroku logs is: File "/app/input/merge.py", line 69, in merge 2019-12-02T07:55:48.252446+00:00 app[web.1]: document.write('documents/'+name+'.docx') 2019-12-02T07:55:48.252449+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/mailmerge.py", line 120, in write 2019-12-02T07:55:48.252451+00:00 app[web.1]: with ZipFile(file, 'w', ZIP_DEFLATED) as output: I don't understand why it is giving me this error. The documents generated are saved into a folder named documents in the root directory of the project. -
Confusion about the django permission and group model?
For example I create permission like this: Permission.objects.create(name='Can add',codename='can_add',content_type=1) Now if I want to apply this permission in some view I need to use permission_required decorator like this @permission_required('app.can_add', raise_exception=True) def some_view(request): ... Here I need to exactly match the permission code_name in the decorator in order to apply the permission . But what if admin(not developer) created new permission with different codename than the codename which is used in a view? We should go manually to the code and edit the codename ? Or is there any better solutions?How can admin apply the newly created permission in the view without manually going in the code? I am thinking it from the normal user perspective, after we gave the project to the client.How can he/she manage such things? -
How can you call commands in django project?
I want to run a command on a django project but don't know how to call it from cmd I have a class Command(BaseCommand) and a handle method inside my class the python file name is assign_tasks.py. How to call this command on cmd -
django-auth-ldap failed to map the username to a DN after switching to LDAPS
I'm building a django project for my company, I had settings like below when I just use simple bind without SSL: AUTH_LDAP_SERVER_URI = 'ldap://some.example.server:389' AUTH_LDAP_BASE_DN = 'some-base-dn' AUTH_LDAP_BIND_DN = 'some-bind-dn' AUTH_LDAP_BIND_PASSWORD = 'some-password' AUTH_LDAP_USER_SEARCH = LDAPSearch( AUTH_LDAP_BASE_DN, ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)') and it worked perfectly. However, due to the security enhancement of our company's LDAP server, we're asked to use LDAP over SSL. So I get a certificate and change my code like this: AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_X_TLS_REQUIRE_CERT: True, ldap.OPT_X_TLS_DEMAND: True, ldap.OPT_REFERRALS: 0, ldap.OPT_X_TLS_CACERTFILE: '/etc/ssl/certs/mycertfile.pem' } AUTH_LDAP_SERVER_URI = 'ldaps://some.example.server:636' AUTH_LDAP_BASE_DN = 'some-base-dn' AUTH_LDAP_BIND_DN = 'some-bind-dn' AUTH_LDAP_BIND_PASSWORD = 'some-password' AUTH_LDAP_USER_SEARCH = LDAPSearch( AUTH_LDAP_BASE_DN, ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)') It no longer works. It keeps saying search_s(xxx) returned 0 objects: Authentication failed for : failed to map the username to a DN. But if I change the filter string for the LDAPSearch() from '(sAMAccountName=%(user)s)' to '(sAMAccountName=<hard-coded-id>)' it works. I've been trying to dig out why this happens and so far no luck. Does anyone have any idea why this is happening? Much Appreciated. -
How to raise error message if data does not exist in django table
I have my table and filter all set up and working but I wish to have an error functionality added to it in such a way that when I query a data which exist in the db, it should show me the result normally, however, when I input a qs which does not exist, it should show me a message on the table that says "record does not exist" instead of a blank table. Here is my view: from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.shortcuts import render from django_tables2 import RequestConfig from django_tables2.export import TableExport from .models import Employee from .models import EmployeeFilter from .tables import EmployeeTable @login_required() def employees(request): filter = EmployeeFilter(request.GET, queryset=Employee.objects.all()) table = EmployeeTable(filter.qs) RequestConfig(request).configure(table) count = Employee.objects.all().count() male_count = Employee.objects.filter(gender__contains='Male').count() female_count = Employee.objects.filter(gender__contains='Female').count() user_count = User.objects.all().count() export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("table.{}".format("csv", "xlsx")) return render(request, "employees/employees.html", { "table": table, "filter": filter, "count": count, "male_count": male_count, "female_count": female_count, "user_count": user_count, }) -
Specific URL calling
when I call any of URL from urls.py so only the top one URL's result is returned. like I call the second URL name = 'test' or name = 'detail', it will return only the first URL name = 'list', not which I want. urlpatterns = [ url(r'',views.SchoolListView.as_view(),name = 'list'), url(r'',views.TestView.as_view(), name = 'test'), url(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(),name = 'detail'), ] -
Can we send the HttpResponse of django `render()` in a python dictionary?
What my use case is I need whole render() data into a dictionary which will be having other key values too and finally I can return it as a normal Response. Let suppose my code is: from django.shortcuts import render def my_view(request): # View code here... return render(request, 'myapp/index.html', { 'foo': 'bar', }, content_type='application/xhtml+xml') Now what we are doing here is: render is basically returning a HttpResponse which we are returning. What I need is: Save the return response in a variable x = render(request, 'myapp/index.html', { 'foo': 'bar', }, content_type='application/xhtml+xml') Then can we save it in a dictionary to return as a Response? Like this y = {} y = {name: 'testing', render_response: x} return y -
owner is required in Django template
I have two identical views in which I am editing an existing model record Views.py def edit_product(request, pk): instance = get_object_or_404(Product, pk=pk) form = Producteditform(request.POST or None, instance=instance) if form.is_valid(): form.save() return redirect('employee:products_table') return render(request, 'packsapp/employee/employeeProductEditForm.html', {'form': form}) def edit_warehouse(request, pk): instance = get_object_or_404(Warehouse, pk=pk) form = Warehouseeditform(request.POST or None, instance=instance) if form.is_valid(): form.save() return redirect('employee:warehouse_table') return render(request, 'packsapp/employee/warehouseEditForm.html', {'form': form}) Forms.py class Producteditform(forms.ModelForm): class Meta: model = Product fields = '__all__' class Warehouseeditform(forms.ModelForm): class Meta: model = Warehouse fields = '__all__' Models.py class Warehouse(models.Model): owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='employee_warehouse_owner') warehouse_name = models.CharField(max_length=500, default=0) warehouse_email = models.EmailField(max_length=500, default=0) warehouse_contact = models.CharField(max_length=500, default=0) class Product(models.Model): product_id = models.IntegerField(default=0) product_quantity = models.IntegerField(default=0) product_hsn_code = models.IntegerField(default=0) product_owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='product_owner') When I edit a product it saves the form without any error but when i try to do the same with warehouse it refreshed without any error and was not proceeding. Then with {{ form.errors }} it says : owner This field is required. Why does it need owner in the warehouse edit form but not in the product edit form ? -
django-storages EndpointConnectionError
Sorry for the noise but I think I am missing something and I can't find my solution. When running my collectstatic, I get the following error: botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "http://localhost:1212/test/static/gis/css/ol3.css" Here is the following setup: docker-compose.yaml . . . s3server: image: scality/s3server:latest restart: unless-stopped ports: - "1212:8000" volumes: - s3data:/usr/src/app/localData - s3metadata:/usr/src/app/localMetadata environment: SCALITY_ACCESS_KEY_ID: newAccessKey SCALITY_SECRET_ACCESS_KEY: newSecretKey SSL: "FALSE" settings.py # AWS settings AWS_ACCESS_KEY_ID = env.str('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env.str('AWS_SECRET_ACCESS_KEY') AWS_S3_REGION_NAME = env.str('AWS_S3_REGION_NAME') AWS_STORAGE_BUCKET_NAME = env.str('AWS_STORAGE_BUCKET_NAME') AWS_S3_ENDPOINT_URL = env.str('AWS_S3_ENDPOINT_URL') AWS_DEFAULT_ACL = None AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_QUERYSTRING_AUTH = False # s3 static settings AWS_STATIC_LOCATION = 'static' STATIC_URL = f'http://{AWS_S3_ENDPOINT_URL}/{AWS_STATIC_LOCATION}/' STATICFILES_STORAGE = 'backend.storages.StaticStorage' # s3 media settings AWS_MEDIA_LOCATION = 'media' MEDIA_URL = f'http://{AWS_S3_ENDPOINT_URL}/{AWS_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'backend.storages.PublicMediaStorage' dev.env AWS_STORAGE_BUCKET_NAME=test AWS_ACCESS_KEY_ID=newAccessKey AWS_SECRET_ACCESS_KEY=newSecretKey AWS_S3_REGION_NAME=us-east-1 AWS_S3_ENDPOINT_URL=http://localhost:1212 backend/storages.py class StaticStorage(S3Boto3Storage): location = settings.AWS_STATIC_LOCATION default_acl = "public-read" class PublicMediaStorage(S3Boto3Storage): location = settings.AWS_MEDIA_LOCATION default_acl = 'public-read' file_overwrite = False I really don't understand why as the following script works just fine: script.py import logging import boto3 from botocore.exceptions import ClientError s3_client = boto3.client( 's3', aws_access_key_id="newAccessKey", aws_secret_access_key="newSecretKey", endpoint_url='http://localhost:1212', region_name="us-east-1", ) def create_bucket(bucket_name): try: s3_client.create_bucket( Bucket=bucket_name, CreateBucketConfiguration={'LocationConstraint': "us-east-1"}, ) except ClientError as e: logging.error(e) return False return True if __name__ == "__main__": create_bucket("test", region="us-east-1") … -
AsyncWebsocketConsumer VS AsyncConsumer
I'm trying to use Channels2 in my project. it's the first time that I meet channel in Django :) I have two main useful and almost complete sources here: 1)video on youtube DJANGO CHANNELS 2 Tutorial (V2) - Real Time 2)document of Channel in Read The Doc as I don't know what will happen in the future of my code I need you to help me choose using between AsyncWebsocketConsumer as mentioned in source #1, or AsyncConsumer that is used in source # 2 for starting Django channel app that including by this way: from channels.generic.websocket import AsyncWebsocketConsumer from channels.consumer import AsyncConsumer explanation: class AsyncConsumer: """ Base consumer class. Implements the ASGI application spec, and adds on channel layer management and routing of events to named methods based on their type. """ class AsyncWebsocketConsumer(AsyncConsumer): """ Base WebSocket consumer, async version. Provides a general encapsulation for the WebSocket handling model that other applications can build on. """ my goal of using channel: trying to integrated real-time chat, notification/alert/transfer_data to the clients for the specific situations. (now the app working without Websocket with DRF) and if you have any suggestions, ideas or notices I will be very happy to listen.thank you so … -
Django-2.2 NoReverseMatch error. Cannot redirect to next page
After submission of a create form in my web app it should redirect in to a single page where it displays the new product that is entered. instead of that, it shows : Reverse for 'category' with keyword arguments '{'pk': UUID('e3ec4273-22c9-450f-87c9-d12973dce3c1')}' not found. 1 pattern(s) tried: ['app/products/category/<int:pk>'] views.py def create_category(request): if request.method=='POST': form = CategoryForm(request.POST,request.FILES) if form.is_valid(): data = form.save(commit=False) data.creator = request.user data.updater = request.user data.auto_id = get_auto_id(ProductCategory) data.save() return HttpResponseRedirect(reverse('products:category',kwargs={"pk":data.pk})) else: ... else: ... def category(request,pk): instance = get_object_or_404(ProductCategory.objects.filter(pk=pk)) context = { 'title': "Category : " + instance.name, 'instance' : instance, } return render(request,'products/category.html',context) urls.py from django.urls import path from . import views app_name = 'products' urlpatterns = [ path('categories',views.categories,name='categories'), path('category/create',views.create_category,name='create_category'), path('category/<int:pk>',views.category,name='category'), path('category/edit/<int:pk>',views.edit_category,name='edit_category'), path('category/delete/<int:pk>',views.delete_category,name='delete_category'), ] Th thing is the form is submitted and the values are added to database. But it doesn't move to the next step. I am new to django 2 so not very sure on how to pass pk in urls/path -
Page is not showing on ID
In Django when I click on the link which returns an id but the page is not showing in return. here is url, url(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(),name = 'detail') View.py class SchoolDetailView(DetailView): context_object_name = 'school_detail' model = models.School template_name = 'basic_app/school_detail.html' HTML view {% for school in schools %} <h2><li><a href="{{school.id}}">{{school.name}}</a></li></h2> {% endfor %} -
Django 2.2 : How to change verbose_name of default auth app "Authentication and Authorization"?
How can change verbose_name of default auth app in Django Admin, by default it's showing Authentication and Authorization. I just want rename this with Staff Management? Thanks -
Is there a static dead code analyser for Django?
Is there a static dead code analyzer for Django, which excludes such unused variable like 'template_name' or 'form_class' or class 'Meta'. I am looking for a dead code analyzer that reports me only the relevant codes as far as possible. I tried the vulture package, but I want to avoid this: asistar/tests/factories.py:32: unused class 'Meta' (60% confidence) asistar/tests/factories.py:33: unused variable 'model' (60% confidence) asistar/tests/factories.py:47: unused class 'Meta' (60% confidence) asistar/tests/factories.py:48: unused variable 'model' (60% confidence) asistar/tests/factories.py:60: unused class 'Meta' (60% confidence) asistar/tests/factories.py:61: unused variable 'model' (60% confidence) -
How to check if the fields already exist.?
I need to check if the fields already exist. If that field doesn't exist, then I need to create a new one. Like the availability check on a booking system My Model # Choices time = [ ('1', 'Morning'), ('2', 'Afternoon'), ('3', 'Evening'), ('4', 'Night'), ] # Model class Calender(models.Model): user = models.ForeignKey(AUTH_USER_MODEL,on_delete=models.SET_NULL) date = models.DateField() time = models.CharField(max_length=10, choices=time) location = models.CharField(max_length=32) My View class CheckAvailabilityAPIView(APIView): def post(self, request): date = request.data.get('date') time = request.data.get('time') location = request.data.get('location') calender = Calender.objects.all() for obj in calender: if obj.booked_date == date and obj.section_timing == time and obj.location == location: return Response({'response': 'Already exist'}) else: user_id = request.user.id user = User.objects.get(id=user_id) serializer = VendorsCalenderSerializer(data=request.data) if serializer.is_valid(): serializer.save( user=user, date=date, time=time, location=location ) return Response({'response': 'Success', 'result': serializer.data}) else: return Response({'response': 'Failed', 'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) Can someone help me with this.? -
Django Rest Framework, create method is no working properly
There is a trial end field in subscription model, i want to initialize the field with trial_end_date , problem I'm facing now trial_end in subscription model showing null value, How can I extract out the field of trial end field and initialize it? I have attached the def create method looked at that. I will appreciate your help . def create method [Model][2] my aim is when in membership model plan contain trial period days , it will add in trial end field of subscription model -
I want to filter by Today Day and Count ids on that day
I am New To Django Plz help me out But in this Case I want Result as {weekday: todayweek_number, count: total_ids_count_number } Currently I am Using this Django Query as follows Booking.objects.filter(created_at__day=today.day).annotate(count=Count('id')).values('weekday', 'count') The Point here is 'Weekday' I want Today Week Day Number as a key, which I am Using in filter -
How to add 2 models in a registration form in Django?
I want to create a Registration form which includes two models. One model is my custom model (Profile) and the other is the default User model in Django. I created two separate forms within the same template but the data is not successfully stored. This is what I had done so far: models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) company = models.CharField(max_length=100, blank=True, null=True) address = models.TextField() views.py: def register(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('login') else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'register_page.html', {'user_form': user_form, 'profile_form': profile_form}) forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['company', 'address'] However, when I tried to register a new user, the data gets saved in the User model (username, email, password) but not in the Profile model (company, address). I am getting this error instead: RelatedObjectDoesNotExist at / Profile has no user. What should I … -
Override Save Model in Django
What I wanted to do is to override the save button in the model to run my script. My script contains Tensorflow code. So, what I am trying to do is to get the uploaded image to run in my script then the result image will save in the media. My script contains total count value so I would like to save it in the model. Please help. Model.py from django.db import models # Import packages import os import cv2 import numpy as np import tensorflow as tf import sys # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util from utils import visualization_utils as vis_util from api import object_counting_api from django.conf import settings from django.shortcuts import render class District_1_2018(models.Model): barangay = models.CharField(max_length=255) totalarea = models.CharField(max_length=10) image = models.ImageField(upload_to='result/2018/district1') totalcount = models.CharField(max_length=10) def __str__(self): return self.barangay Forms.py class District_1_2018Form(forms.ModelForm): class Meta: model = District_1_2018 fields = ['barangay', 'totalarea', 'image', 'totalcount'] My script # Name of the directory containing the object detection module we're using MODEL_NAME = 'inference_graph' IMAGE_NAME = 'Burol.png' # Grab path to current working directory CWD_PATH = os.getcwd() # Path to frozen detection graph .pb file, which … -
how to create a zoom meeting using a token in django?
i am new to this can someone help? i took help on google and you tube but i cannot able to find any solution. I have been told this to do- Try writing a si.ole python script where - 1. You can obtain oauth token from API. 2. Using the token programmatically create a meeting. -
it is possible to add a keyword to python?
There are many keywords in other languages that miss includes in Python. For example: 'delegate' or 'sealed', 'interface' or 'event' can make the tasks much easier and readable, because you won't have to remember the functionality of the method, but instead use it as a keyword ... If there is no possible way to add a keyword and warn the interpreter from it, then ** please support this message ** so Python Foundation might see it, and consider this feature. 1. class Animals(abc.ABC): @abstractmethod def walk(...): pass 2. interface Animals: def walk(...): pass -
ImportError: No parent package available
This is my line: from . import views This is the error: ImportError: attempted relative import with no known parent package