Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add custom query / queryset to Django Admin?
I'm building a Django project and have a model called Animal. Something like: class Animal(models.Model): type = models.CharField() In the django admin interface I can easily see all animals which is awesome. However I would like to add 2 additional views to the admin so that I can see all animals of a certain type: For example if my Admin view could look like this: Animals -> Shows all animals (default) Animals (type == dog) -> Shows only dogs Animals (type == cat) -> Shows only cats Any advice or best practices on how to do this? Thanks. -
Can't log into heroku using bash command line for Django
I'm trying to deploy my first django app on heroku but i am not being able to do so. I have done pip install django-heroku and also done a pip freeze to requirements.txt . I also installed guincorn and psycopg2 according to a tutorial. All the installations are in a virtual env. I am currently using bash command line from windows (on vscode). When i do heroku login it shows bash: heroku: command not found. What should I do? -
How to escape the required login in Django?
A Django web application usually has login required, however there is a url or view that does not need to have a login_required. How to make it work? -
Django: How to create an user and set a related field
I've extended the user data using another model (OneToOne relation) and when a user is created, its profile is also created. I'd like to update the field mailing when the user is created without a query. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mailing = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py def register(request): ... if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.mailing = profile_form.cleaned_data['mailing'] user.save() #The user is created but mailing is not set return redirect('login') profile_backend.py class ProfileBackend(ModelBackend): def get_user(self, user_id): UserModel = get_user_model() try: return UserModel._default_manager.select_related('profile').get(pk=user_id) except UserModel.DoesNotExist: return None I can set the variable taking the user as object but this imply using an extra function. -
UpdateView using foreignkey in Django
Is there a way that instead of pk i will select the model data by foreign key in UpdateView? It is no doubt it works on the id of the data but what if i will select the data object in the model using foreign key condition? How would i do that? Here is my UpdateView class: class SettingsProfileView(UpdateView): model = UserInfoModel template_name = 'site/views/settingsprofile.html' form_class = UserInfoForm I try to put: def getquery_set(self): return self.model.objects.filter(users_id = self.kwargs['pk']) but still its refering to get the data by primary key. -
Does using post_save and post_delete methods slow down over all Django project speed?
I want to keep track of number of database entries. I do not want to use (in my case) Book.objects.all().count(). I know it works quite fast, but I do not think it is the good way. I have implemented Tracker class and I will be working with that singleton type of class if the numbers are needed. Question: Does using post_save and post_delete slow down my Django project? my source code models.py from django.db.models.signals import post_save, post_delete from django.db import models class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class Book(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tracker(Singleton): def __init__(self): self.__count = self.__get_numbers() def __get_numbers(self): print("I am getting records") return Book.objects.all().count() @property def count(self): return self.__count def update_record_count(sender, **kwargs): tracker = Tracker() print("Database entries: {}".format(tracker.count)) post_save.connect(update_record_count, sender=Book) post_delete.connect(update_record_count, sender=Book) What I have written above is truely imaginative, just for learning purposes -
Filtering searches with Django filters, query gets deleted
I've been coding an ecommerce app with Django and I'm in the proces of creating a filtering system for the searches. This is the listview that displays the items: class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 2 def get_queryset(self): qs = self.model.objects.all().order_by('id') search = self.request.GET.get('q') if search: qs = qs.filter(Título__icontains=search) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MyFilter = PubFilters(self.request.GET, queryset=self.get_queryset()) context['filter'] = MyFilter context['filtered_items'] = MyFilter.qs context['count'] = self.get_queryset().count() context['búsqueda'] = self.request.GET.get('q') return context This is the filter: import django_filters from .models import publicaciones class PubFilters(django_filters.FilterSet): o = django_filters.OrderingFilter( fields=( ('Fecha', 'Más nuevo'), ), ) class Meta: model = publicaciones fields = ['Precio', 'Categoría'] The problem is that if I search something and then try to apply a filter, the query that I searched is deleted, and displayed by "None". Any help will be appreciated EDIT: This is the template: {% extends 'store/store.html' %} {% load static %} {% load crispy_forms_tags %} <link rel="stylesheet" type="text/css" href="{% static 'css/style_search.css' %}"> {% block content %} <div class="container"> <form method="GET"> {{ filter.form|crispy }} <button class="btn btn-primary" type="submit">Buscar</button> </form> </div> <h3>{% if count == 0 %} Ningún resultado para {% elif count == … -
Django GraphQL django-graphql-jwt token not working in self-signed ssl server
I'm using django-graphql-jwt for GraphQL API authentication. Deployed to ubuntu server with self-signed ssl. Here is the mutation for authentication mutation { tokenAuth(email: "example@test.com", password: "password") { token } } So I used this token for authorization. Request Header: Authorization: JWT <token> Request Body: query { me { username firstName lastName email phone } } Result: { "errors": [ { "message": "'AnonymousUser' object has no attribute 'email_verified_at'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "me" ] } ], "data": { "me": null } } This is correctly working in none-secure server(http). How can I fix this issue? Regards. -
Python Django: Customize Admin Startpage as analytical Dashboard
I am currently developing a mobile app using Ionic and I am using Django Admin Interface as sort of Backend for adding and editing the content of my mobile app through a MySQL Database. I currently wish to create a custom analytical dashboard for tracking the usage of the users of my mobile app in the startpage of the Django Admin. While there are some analytical packages for tracking the usage in Django, they only function for web applications. In my case I need to gather and display aggregate data from my database (Django models & not Django models) as well for other APIs. Is there a way how can I fetch data in form of SQL queries and display them in my dashboard using Python (Django)? And how can I extend the starting page of Django Admin to a full analytical dashboard with the named functionalities? I am currently struggling with this as I am new to Django. Any help is much appreciated! -
Django. IntegrityError: NOT NULL constraint failed: MyApp_song.albums_id
For starters, I just started learning Django. I'm trying to add a new song object to my album via the form. But I don't want to manually select the album (my foreign key) that I want to add a new song to. Instead, I want the value of my foreign key to be set depending on the album I'm adding a new song from. How can i do that in Django? I tried to do it like this: views.py class SongCreate(CreateView): template_name = 'music/album_form.html' # fields = ['albums', 'file_type', 'song_title', 'audiotrack', 'is_favorite'] model = Song fields = ['file_type', 'song_title', 'audiotrack', 'is_favorite'] def form_valid(self, form): album = get_object_or_404(Album, pk=self.kwargs['pk']) form.instance.album = album return super(SongCreate, self).form_valid(form) urls.py path('music/album/<int:pk>/add', views.SongCreate.as_view(), name='song-add'), models.py class Song(models.Model): albums = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) audiotrack = models.FileField(upload_to='media/') is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('param', kwargs={'pk': self.albums.id}) def __str__(self): return self.song_title Link to add a new album <a href="{% url 'song-add' album.id %}">Add album</a> But for some reason it doesn't work, although I thought it should help. So i'm getting this error. Maybe you know what's the problem? Thanks, any help will be appreciated! -
How do I upgrade an old Django Google App Engine application to a Second Generation Cloud SQL Instance?
I have a Django application that I wrote 5 years ago, which has been running successfully on Google App Engine - until last month when Google upgraded to Second Generation Cloud SQL. Currently, I have a settings.py file, which includes a database definition which looks like this: DATABASES = { 'default': { 'ENGINE': 'google.appengine.ext.django.backends.rdbms', 'INSTANCE': 'my-project-name:my-db-instance', 'NAME': 'my-db-name', }, Google's upgrade guide, tells me that the connection name needs to change from 'my-project-name:my-db-instance' to 'my-project-name:my-region:my-db-instance'. That's simple enough. Changing this leads me to get the error InternalError at /login/ (0, u'Not authorized to access instance: my-project-name:my-region:my-db-instance') According to this question, I need to add the prefix '/cloudsql/' to my instance name. So, I changed this (and the ENGINE specification) to give: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'INSTANCE': '/cloudsql/my-project-name:my-region:my-db-instance', 'NAME': 'my-db-name', 'USER' : 'root', 'PASSWORD': '******************', }, I uploaded the modified file to Google (using gcloud app deploy). This time I get a completely different error screen, showing: Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. When I look in the Logs, I see: ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb It was pointed out … -
check if the directory name is year python [duplicate]
how can I check if the directory name is a year using python ? If I have directories called 2018, 2019, 2020, test1, test2, I want to get only directories which name is a year . in this case I want directories with name : 2018, 2019, 2020 -
Filter queryset inside a form
I have one app that holds a list of work orders, and another app that holds list of parts. class Order(models.Model): parts = models.ManyToManyField(Part, blank=True) # Assosiated parts class Part(models.Model): partnum = models.CharField(max_length=20) # Part number mwos = models.ManyToManyField('mtn.Order', blank=True) # Assosiated work orders Now i want to add a button to my DetailView for order which will open a list of parts, which i will be able to add to my order. At the moment i have a created an UpdateView for my order class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order form_class = AddPartForm ... and a form class AddPartForm(forms.ModelForm): class Meta: model = Order fields = ['parts', ] labels = {'parts': "Parts", } def FilterList(request): qs = Part.objects.all() search_part_query = request.GET.get('search_part') if is_valid_queryparam(search_part_query): qs = qs.filter(Q(partnum__icontains=search_part_query) | Q(descr__icontains=search_part_query) ).distinct() return qs def __init__(self, *args, **kwargs): super(AddPartForm, self).__init__(*args, **kwargs) self.fields["parts"].widget = CheckboxSelectMultiple() self.fields["parts"].queryset = self.FilterList() for this template {% block content %} <form method="GET" action="."> <div class="form-row justify-content-start"> <div class="form-group col-md align-self-center"> <div class="input-group"> <input class="form-conrol py-2 border-right-0 border" type="search" placeholder="Find part" name="search_part"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <button type="submit" class="btn btn-primary btn-sm btn-block">Search</button> </form> <form action="{% url 'mtn:add_part' order.id %}" … -
Context in Django HttpResponse
I happen to pass by Django documentation for TemplateResponse. (My question is for HttpResponse) Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the template and context that was provided by the view to compute the response. Here it says that response object which we get from self.client.get() which is an object of HttpResponse, does not retain the context provided by view. But when I did dir(response) I could find context there. Kindly explain me the actual meaning of documentation. -
Does using pre_save or post_save slow down overall Django project?
I need to keep track of Database records count. I was wondering if using post_save or pre_save methods slow down overall Django project's performance. Question: Does using post_save or pre_save signals slow down overall Django project's performance? -
connecting button to modal with bootstrap
I need some help connecting a button which pops up a modal to submit form. this is my html before the modal (works fine and another page is rendered after button is clicked) <div class="container my-container"> <h3> Let's get started </h3> <div class="row my-row"> <h4>1. CSV file</h4> </div> <div class="row my-row"> <h4>2. There should be only two columns</h4> </div> <div class="row my-row"> <form method="post" enctype="multipart/form-data"> {%csrf_token%} <input type="file" name="document"><br> <button type="submit"> Submit</button> </form> </div> </div> I have added the modal but I now have a couple of issues <div class="container my-container"> <div class="row my-row"> <h3> Let's get started </h3> </div> <div class="modal fade" id="demo123"> <div class="modal-dialog"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal"> <span> &times; </span> </button> <div class="modal-header"> <h2 class="modal-title"> Confirm upload </h2> </div> <div class="modal-body"> <p>this is the file name</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Confirm </button> </div> </div> </div> </div> <div class="row my-row"> <h4>1. CSV file</h4> </div> <div class="row my-row"> <h4>2. There should be only two columns titled</h4> </div> <div class="row my-row"> <form method="post" enctype="multipart/form-data"> {%csrf_token%} <input type="file" name="document"><br> <button class="btn btn-primary" data-toggle="modal" data-target="#demo123"> Submit </button> </form> </div> </div> First issue I have is the "submit" button automatically makes the upload(renders to another page). How … -
Django WAMP (Apache) mod_wsgi on Windows
Im new to Django and web development. I have completed a project in development environment and now we need to deploy it in production. I have been trying to go through the deployment process using wamp on a windows virtual machine. The details are as under: OS: Windows 10 Python: 3.7.6 Webserver: Wamp 3.2 with Apache 2.4.41 mod_wsgi ver 4.7.1 (this was downloaded pre-compiled from here Im using pycharm for the development and the default python interpreter path is of system i.e. C:\Users\User\AppData\Local\Programs\Python\Python37 which includes the installed/ extracted mod_wsgi packages in site-packages. The 'Django' package is installed however within venv at C:\Users\User\TryProject\venv\Lib\site-packages I configured my files as folows: httpd-vhosts.conf: <VirtualHost *:8080> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Users/User/TryProject/TryProject.error.log" CustomLog "C:/Users/User/TryProject/TryProject.access.log" combined #WSGIDaemonProcess TryProject python-home=C:/Users/User/TryProject/venv/Lib/site-packages #python-path=C:/Users/User/TryProject/venv/Lib/site-packages #venv/Lib/site-packages" #WSGIProcessGroup TryProject WSGIScriptAlias /mysite "C:/Users/User/TryProject/TryProject/wsgi.py" #process-group=TryProject #application-group=%{GLOBAL} WSGIApplicationGroup %{GLOBAL} <Directory "C:/Users/User/TryProject/TryProject"> <Files wsgi.py> Require all granted </Files> </Directory> httpd.conf: ... LoadFile "c:/users/user/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/user/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/user/appdata/local/programs/python/python37" ... and wsgi.py import sys from django.core.wsgi import get_wsgi_application #site.addsitedir("C:/Users/User/AppData/Local/Programs/Python/Python37/Lib/site-packages") site.addsitedir("C:/Users/User/TryProject/venv/Lib/site-packages") # Add the app's directory to the PYTHONPATH #sys.path.append('C:/Users/User/TryProject') sys.path.append('C:/Users/User/TryProject/TryProject') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TryProject.settings') application = get_wsgi_application() while the apache error log file shows this group of error on every request: [Tue Apr 07 20:18:44.672498 2020] [wsgi:error] [pid 12456:tid … -
How to post in bulk in Django-Rest-Framework with a different format
My Model : from django.db import models Create your models here. from rest_framework.exceptions import ValidationError class Results(models.Model): test_taker = models.ForeignKey('users.User', null=True, related_name='testtakerId', on_delete=models.CASCADE) question_detail = models.ForeignKey('questions_detail.Questions_detail', null=True, related_name='answersId', on_delete=models.CASCADE) test_id = models.IntegerField(null=True) answer = models.CharField(max_length=255, null=True) custom_answer = models.CharField(max_length=255, null=True) What i Want to post: { "test_taker": 1, "test_id": 1, "question": [ { "question_id": 1, "answer": 2, "custom_answer": "c1" }, { "question_id": 2, "answer": 3, "custom_answer": "c2" }, { "question_id": 3, "answer": 4, "custom_answer": "c3" }, { "question_id": 2, "answer": 1, "custom_answer": "c4" } ] } Cuurently what i am doing is: In my views.py : (I am using rest_framework_bulk) class AddResult(ListBulkCreateUpdateDestroyAPIView): lookup_field = 'pk' serializer_class = ResultsSerializer def get_queryset(self): return Results.objects.all() def perform_create(self, serializer): test_taker = self.request.data['test_taker'] test_id = self.request.data['test_id'] serializer.save(test_taker=test_taker, test_id=test_id) My Serializer: class ResultsSerializer(BulkSerializerMixin,serializers.ModelSerializer): class Meta: model = Results fields = '__all__' list_serializer_class = BulkListSerializer What is happening is it just stores 1 result and that has test_taker = 1 and test_id = 1 which it takes from the outer part of the JSON. What i want is for it to store all the records in the format of [test_taker , test_id, question_id , answer, custom_answer] Thanks in advance for positive responses. -
python-social-auth redirect to the user profile in Django
I am using the wonderful python-social-authpackage, and more precisely the social-auth-app-django version since my project is using the Django Framework. Once the user is registered/logged in via any social backend, I'd like to redirect the user to their own very user profile. I know I can set a static URL in my settings.pysuch as: SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/logged-in/' But how can I dynamically redirect the user to their profile given that I know their username/slug? If I could set variables in the settings.py it'd be something like: SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/accounts/<slug:slug>/' But of course I can't do that. Is there any way I can achieve what I want? -
NameError: name 'LoginView' is not defined
I'm installing the Openstack Stein Horizon service (dashboard) following the tutorial on the site. I encounter an error due to the Django version and fix it using this explanation Switch from django string_concat to format_lazy. The next issue that appears was AttributeError: module 'django.contrib.auth.views' has no attribute 'login', which I googled and came again as a Django version incompatibility. I followed this explanation here: AttributeError: module Django.contrib.auth.views has no attribute openstack_auth/urls.py from django.conf.urls import url from django.views import generic from openstack_auth import utils from openstack_auth import views from . import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r"^login/$", LoginView.as_view(), name='login'), url(r"^logout/$", LogoutView.as_view(), name='logout'), url(r'^switch/(?P<tenant_id>[^/]+)/$', views.switch, name='switch_tenants'), url(r'^switch_services_region/(?P<region_name>[^/]+)/$', views.switch_region, name='switch_services_region'), url(r'^switch_keystone_provider/(?P<keystone_provider>[^/]+)/$', views.switch_keystone_provider, name='switch_keystone_provider') ] if utils.is_websso_enabled(): urlpatterns += [ url(r"^websso/$", views.websso, name='websso'), url(r"^error/$", generic.TemplateView.as_view(template_name="403.html")) ] apache2/error.log Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/wsgi.py", line 141, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception callback, param_dict = resolver.resolve_error_handler(500) File "/usr/local/lib/python3.6/dist-packages/django/urls/resolvers.py", line 584, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 80, in … -
Localhost webpage created in django is showing wrong page source code
I am following corey schafer django course using sublime text 3. After i used bootstrap template, my home page was updated. But page named 'about' is not updated. When i use view page source, it is showing wrong source code. My html code for about page is- {% extends "blog/base.html" %} {% block content %} <h1>About Page</h1> {% endblock content %} but when i press view source code it is showing the old one- <!DOCTYPE html> <html> <head> <title>Django Blog-About</title> </head> </head> <body> <h1>About page</h1> </body> </html> My home webpage using the same template got updated, but not this one. My base html file is- <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% if title %} <title>Django Blog-{{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <div class="container"> {% block content %} {% endblock %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> -
Celery worker permission denied
To be quite honest I do not really know what I am doing ;) Recently I installed Mayan EDMS in a chroot on my NAS. So far I got it working ... at least I can login and so forth. But I cannot upload any files and I guess this has to do with celery (which I did not knew about before). Because I am in a chroot I cannot use supervisord for these celery workers and I started them from the command line. e.g. nice -n 19 /path/to/my/mayan-edms/bin/celery worker -A mayan -Ofair -l ERROR -Q statistics,tools,common_periodic,parsing,document_states,mailing,ocr -n mayan-worker-slow.@%h --concurrency=1 But this throws an error: -------------- mayan-worker-slow.@DiskStation213 v4.3.0 (rhubarb) ---- **** ----- --- * *** * -- Linux-3.2.40-armv7l-with-glibc2.17 2020-04-07 15:15:07 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: mayan:0x41cc8d00 - ** ---------- .> transport: redis://:**@127.0.0.1:6379/0 - ** ---------- .> results: redis://:**@127.0.0.1:6379/1 - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> common_periodic exchange=common_periodic(direct) key=common_periodic .> document_states exchange=document_states(direct) key=document_states .> mailing exchange=mailing(direct) key=mailing .> ocr exchange=ocr(direct) key=ocr .> parsing exchange=parsing(direct) key=parsing .> statistics exchange=statistics(direct) key=statistics … -
how to use password field in serializers.py ..password2=serializers.Charfield(serializers.widget=PasswordInput()) doesnot work as it use
AttributeError: module 'rest_framework.serializers' has no attribute 'PasswordInput' serializer.py : from rest_framework import serializers from django.contrib.auth.models import User class SampleSerializer(serializers.ModelSerializer): password2 = serializers.CharField(widget=serializers.PasswordInput()) class Meta: model = User fields = ['username','email','password'] -
Is there any way to use tika library on pythonanywhere?
I'm working on a parsing problem and have used tika library in local system to read pdf documents. As now I'm deploying my parser on the web, I'm not allowed to use tika library on pythonanywhere server. File "/home/mubasharnazar/mysite/server.py", line 114, in read_pdf file_data = parser.from_file(file) File "/home/mubasharnazar/.virtualenvs/flaskk/lib/python3.7/site-packages/tika/parser.py", line 40, in from_file output = parse1(service, filename, serverEndpoint, headers=headers, config_path=config_path, requestOptions=requestOptions) File "/home/mubasharnazar/.virtualenvs/flaskk/lib/python3.7/site-packages/tika/tika.py", line 338, in parse1 rawResponse=rawResponse, requestOptions=requestOptions) Any solution? -
Django command running a shell script
I have an app that deletes files that have been uploaded more than one month ago. from django.core.management.base import BaseCommand, CommandError from blacklist_app.models import EntradaHistorial from datetime import datetime, timedelta import pytz, subprocess, os from blacklist.settings import BASE_DIR class Command(BaseCommand): help = "Procesa archivos en cola para ser movidos al servidor de destino acorde a la configuración" tmp = os.path.join(BASE_DIR, 'blacklist_app/tmp') excel = os.path.join(BASE_DIR, 'blacklist_app/uploaded_files/excel') json = os.path.join(BASE_DIR, 'blacklist_app/uploaded_files/json') mv = 'mv {}/{} {}' rm = 'rm {}/{}' def handle(self, *args, **options): max_date = datetime.now() + timedelta(weeks=-1) preg = "*_{}*".format(max_date.strftime('%Y%m')) #Se mueven los archivos que deben ser conservados a la carpeta temporal self.mv_and_rm(self.excel, preg) self.mv_and_rm(self.json, preg) max_date.replace(day=1, hour=0, minute=0, tzinfo=pytz.UTC) #Actualiza los valores de los archivos borrados EntradaHistorial.objects.filter(fecha__lt=max_date, archivo_borrado=False).update(archivo_borrado=True) # Mueve los archivos a la carpeta temporal, borra los archivos que deben ser borrados y # mueve de vuelta los archivos que deben ser conservados def mv_and_rm(self, dir, preg): move = self.mv.format(dir, preg, self.tmp) self.run_command(move) rm = self.rm.format(dir, '*') self.run_command(rm) move_back = self.mv.format(self.tmp, preg, dir) self.run_command(move_back) def run_command(self, command): sh = os.path.join(BASE_DIR,'blacklist_app/management/commands/run_command.sh') call = "sh {} '{}'".format(sh, command) print(subprocess.check_output(call)) In the same directory I have the script run_command.sh #!/bin/sh $1 This command should run in the crontab on the first …