Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which package should i use with django to implement social login in august 2017?
I started development with Python Django and explored so many packages like python-social-auth, Django-all-auth, and Django-social-auth. After Lots of research, I found that all packages have their pros and cons. Like Django-social-auth was deprecated and merged into python-social-auth and now I found auth that Python-social-auth also has been deprecated. Django All Auth has lots of problems when it comes to creating a custom model. So Now I'm really confused what to choose and need help in this.I want to choose the one for which I will get longer support and good for lot of customizations. -
Django CreateView with form_class not creating model
I'm practicing from Two Scoops of Django book and i have a problem with form_class in CreateView. If i'm using just fields in the CreateView it's saving the model, if i'm using the form_class it's not saving and not redirecting either. I'm using form_class for practicing validators. views.py class FlavorCreateView(LoginRequiredMixin, CreateView): model = Flavor success_url = '/flavors/list/' template_name = 'flavor_create.html' success_msg = 'Flavor created.' form_class = FlavorForm # fields = ['title', 'slug', 'scoops_remaining'] def form_valid(self, form): form.instance.created_by = self.request.user return super(FlavorCreateView, self).form_valid(form) forms.py class FlavorForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FlavorForm, self).__init__(*args, **kwargs) self.fields['title'].validators.append(validate_tasty) self.fields['slug'].validators.append(validate_tasty) class Meta: model = Flavor fields = ['title', 'slug', 'scoops_remaining'] validators.py def validate_tasty(value): """ Raise a ValidationError if the value doesn't start with the word 'Tasty'. """ if not value.startswith('Tasty'): msg = 'Must start with Tasty' raise ValidationError(msg) flavor_create.html {% extends 'base_flavor.html' %} {% block content %} <form action="" method="POST">{% csrf_token %} <p style="color: red;">{{ form.title.errors.as_text }}</p> {% for field in form %} <p>{{ field.label }}: {{ field }}</p> {% endfor %} <button type="Submit">Salveaza</button> </form> <a href="{% url 'flavors:list_flavor' %}">Return home</a> {% endblock %} -
How to log out using rest framework jwt
How to log out using rest framework jwt. How can I close the existing token for the logged in user? Just as there is a get_jwt_token function, is there a function to break or close? Thank you very much -
recive message from user with telegram bot - Django
I have a bot and a website and i want when a user send me a command (i set command in past) and i just replay to user his message and write some thing to user : For example : user : /message mybot : (replay his message)you send me a command But i dont know how to recive his command(or message). My coding language in django.(if there is a way with php tell me too) note : bot send updaytes to website and website send again message to bot. note : if there is project on github or some result for me in here(stackovwerflow),tell me . -
Django date time filter?
I have a createdAt field in my database which stores the current time stamp.And when I render it to my templates it returns in the form of Aug. 24, 2017, 12:58 p.m.. What I want it to return in the form of Aug. 24, 2017, 12:58 PM.That is am/pm should be in caps form. what I tried in my templates are:- <td>{{ item.newsId.createdAt|time:"g:iA" }}</td> and what it returned is only time 10:27AM.But I want the date also along with this time format. -
Access to fields of on reverse relation in django
I have this models: class Task(models.Model): user = models.ForeignKey(User) name = models.CharField() class Report(models.Model): task = models.ForeignKey( Task, blank=True, null=True, related_name='+') status = models.CharField(max_length=32, choices=Status.CHOICES, default=Status.INCOMPLETE) now I want to get all Task and related status. How do I access all task and related status? Thanks a lot in advance! -
django-background-tasks doesn't execute Pool.map_async
I want to execute some tasks in parallel, and I want to start them using django-background-tasks. To that end, I collect a number of such tasks in a batch, and then I use django-background-tasks to schedule the execution of that batch, which itself is executed using multiprocessing.pool.Pool.map_async. The code is rather simple: def new_calc(diff_ids): <<some code to calculate things>> @background(schedule=0) def multiproc_calc(diff_ids, workers): with Pool(workers) as p: res = p.map_async(new_calc, diff_ids, chunksize=8) return res.get() if __name__ == "__main__": diffs = <<some logic to gather diff ids>> multiproc_calc(diffs, 8) This logic works on my local machine, however, when I install it on our stage machines, the multitreading calls don't seem to get called. As soon as I run manage.py process_tasks, the background_task_completedtasks is immediately filled in with the entries stating that the calls have been successful, but the calculations that they should have done aren't there. I can't figure out if this is the configuration issue on the stage server and how to look for it. -
Updating front end data as backend does analysis
I've been self studying web design and want to implement something, but I'm really not sure how to accomplish it, even if I can. The only frontend I have dealt with is angular 4, and the only backend I have dealt with is django rest framework. I have managed to get user models done in drf, and the frontend to get the user authenticated with json web tokens, and done different kinds of get and post requests. What I want to do is on the front end have a button, when the button is hit, it will send some get request, that basically runs a text mining algorithm that will produce a list, it may take some time to fully complete, maybe in the range of 20-30 seconds, but I don't want the user to wait that long to get back the single response containing the fully compiled list. Is it possible to say create a table in angular, and then every couple of seconds the backend sends another response containing more data, where the backend then appends the new results to that table. Something like: 00.00s | button -> GET request 01.00s drf starts analysis 05.00s drf returns the … -
Django: In memory database django.db.backends.sqlite3 + SessionMiddleware?
I'm using django 1.10.5 with py34. I would like to configure the database such that everything happens in memory: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } I also want to overwrite the user authentication as explain here because the login and password must be loaded from my own conf.ini file. After doing the modification, I get the error: OperationalError at / no such table: django_session During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: Is it impossible to use the middleware django.contrib.sessions.middleware.SessionMiddleware with an in memory database ? -
Signature error message when uploading file with fineuploader into django
I'm setting up a file upload system with fine uploader and django 1.11. I setup the urls, template and view but here are the (client) error messages I get when attempting to upload a file: [Fine Uploader 5.15.0] POST request for 0 has failed - response code 400 [Fine Uploader 5.15.0] Error attempting to parse signature response: SyntaxError: JSON Parse error: Unexpected identifier "invalid" [Fine Uploader 5.15.0] Received an empty or invalid response from the server! [Fine Uploader 5.15.0] Policy signing failed. Received an empty or invalid response from the server! Fine uploader requires in django settings : AWS_CLIENT_SECRET_KEY = IAM user Secret access key AWS_SERVER_PUBLIC_KEY = IAM user Access key ID AWS_SERVER_SECRET_KEY = IAM user Secret access key I have my Access key ID and Secret access key from the iam user I created and set them as shown above. AWS_CLIENT_SECRET_KEY = AWS_SERVER_SECRET_KEY = IAM user secret key. I'm not sure this is correct and it might well be the problem, but I have no clue what is the difference between AWS_CLIENT_SECRET_KEY and AWS_SERVER_SECRET_KEY and where to find them if one is not iam secret key. And here is the code: View: from django.shortcuts import render from django.conf import … -
can i use DefaultRouter with CreateAPIView in django rest?
when I try to add my CreateAPIView to router.register it rise TypeError exception: File "/home/denys/.virtualenvs/buddha_test/lib/python3.5/site-packages/rest_framework/routers.py", line 281, in get_urls view = viewset.as_view(mapping, **route.initkwargs) TypeError: as_view() takes 1 positional argument but 2 were given But if I add url directly to urlpatterns it works! The resone is that I whant to see link in API Root: enter image description here So quation is can I write something like this: urls.py from django.conf.urls import url, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'clients-list', views.ClientList) router.register(r'managers-list', views.ManagerList) router.register(r'clients', views.CleintCreate, base_name='create') urlpatterns = [ url(r'^', include(router.urls)), ] views.py from .models import Client, Manager from .serializers import ClientSerializer, ManagerSerializer from rest_framework import generics from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.generics import CreateAPIView from rest_framework.decorators import detail_route class ClientList(viewsets.ModelViewSet): permission_classes = (IsAuthenticated, ) queryset = Client.objects.all() serializer_class = ClientSerializer class ManagerList(viewsets.ReadOnlyModelViewSet): permission_classes = (IsAuthenticated, ) # queryset = Manager.objects.all() serializer_class = ManagerSerializer class CleintCreate(CreateAPIView): model = Client serializer_class = ClientSerializer permission_classes = (AllowAny,) -
Creating a User Profile page using OneToOne field with User Model
I'm currently using Django all-auth, and it has a /accounts/profile page which I want to create/populate with a form which updates user information. I have a Teacher field, which extends the User Model using OneToOne field. models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher') bio = models.TextField(max_length=500, blank=True) availability = models.BooleanField(default=False) teacher_logo = models.FileField() This teacher model is what I want the user to update in /accounts/profile. forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') class TeacherForm(forms.ModelForm): class Meta: model = Teacher fields = ('availability', 'bio','teacher_logo') views.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) teacher_form = TeacherForm(request.POST, instance=request.user.teacher) if user_form.is_valid() and teacher_form.is_valid(): user_form.save() teacher_form.save() messages.success(request, _('Your profile was successfully updated!')) return redirect('users:index') else: messages.error(request, _('Please correct the error below.')) else: user_form = UserForm(instance=request.user) teacher_form = TeacherForm(instance=request.user.teacher) return render(request, 'accounts/profile.html', { 'user_form': user_form, 'teacher_form': teacher_form }) template users/profile.html <form method="post"> {% csrf_token %} {{ user_form.as_p }} {{ teacher_form.as_p }} <button type="submit">Save changes</button> </form> urls.py url(r'^profile/$', views.update_profile, name='Update-Profile') I can use an update view, but then I need to specify in the URL, which seems an incorrect way of doing it; Also, users will be able to edit someone else profiles. When … -
when trying to open admin page on model obj it never loads
i have a project i have been building for a while and i recently noticed an issue. this is using python 3.6 and Django 1.11 I have the following model class Mail(models.Model): """ This stores all Downloaded Mails. They relate To alerts raised by the email checking process. """ # This is for turning column numbers into ordering commands ordering = { '0': { 'asc': 'mail_from', 'desc': '-mail_from' }, '1': { 'asc': 'subject', 'desc': '-subject' }, '3': { 'asc': 'received', 'desc': '-received' } } mail_id = models.CharField(unique=True, max_length=255) mail_from = models.EmailField() subject = models.CharField(max_length=255) message = models.TextField() alert = models.ForeignKey(Alert, null=True, blank=True) received = models.DateTimeField(default=timezone.now, db_index=True) processed = models.BooleanField(default=False) class Meta: """ Mails should be ordered by newest first. get_latest_by should be the received property """ get_latest_by = 'received' ordering = ['-received'] def __str__(self) -> str: """ :return: Return string in the format 'Mail_id: subject_text' :rtype: str """ return f'<{self.mail_id}: {self.subject}>' i can access and read the mails by using my views. i had been displaying them manually but i decided to switch to using a form to show them. then i noticed my issue. it seems to get stuck in an infinite loop putting this model into a form. … -
TypeError: __init__() got an unexpected keyword argument 'max_digits'
In my model, I set the class Account(models.Model): balance = models.FloatField(max_digits=16, decimal_places=2) ... But I get the bellow error: ... File "/Users/luowensheng/Desktop/abc/Project/abc_web/aadmin/models.py", line 9, in <module> class Account(models.Model): File "/Users/luowensheng/Desktop/abc/Project/abc_web/aadmin/models.py", line 11, in Account balance = models.FloatField(max_digits=16, decimal_places=2) TypeError: __init__() got an unexpected keyword argument 'max_digits' I use the python2.7 -
Creating multiple choices field in Django using PostgreSQL's column сontent of type json[]
I've got a problem with taking values from PostgreSQL database and pushing them into multiple choices field in Django form. So I've got a column typed json[] with following content: [{1: a}, {2: b},...] I need to create checkboxes with multiple choices using this array. Every db's row has its own content in this column. Every choice is in its own row: 1) a; 2) b; etc... This field in model looks like "field = JSONField()" How can I do that? Any suggestions? ty. -
backend framework to wrok with elasticsearch
I want an opinion about a good back-end to work with elasticsearch. Currently I am using expressjs and it's pretty cool, its fast and easy to code. But some says use spring-mvc or django instead since these are mostly used in the industry these days. My main concern is speed of retrieval from elasticsearch. Any ideas? -
Scrapyd, Celery and Django running with Supervisor - GenericHTTPChannellProtocol Error
I'm using a project called Django Dynamic Scraper to build a basic web scraper on top of Django. Everything works find in development but when setting up on my Digital Ocean VPS I run into issues. I'm using Supervisor to keep three things running: 1. Scrapyd on 0.0.0.0:6800 2. Celery task scheduler 3. Celery worker Whenever Celery passes a job to Scrapyd to scrape I get an error logged to the Scrapyd log: 2017-08-29T08:49:06+0000 [twisted.python.log#info] "127.0.0.1" - - [29/Aug/2017:08:49:05 +0000] "POST /schedule.json HTTP/1.1" 200 3464 "-" "-" 2017-08-29T08:49:07+0000 [_GenericHTTPChannelProtocol,5,127.0.0.1] Unhandled Error Traceback (most recent call last): File "/home/dean/website/venv/local/lib/python2.7/site-packages/twisted/web/http.py", line 2059, in allContentReceived req.requestReceived(command, path, version) File "/home/dean/website/venv/local/lib/python2.7/site-packages/twisted/web/http.py", line 869, in requestReceived self.process() File "/home/dean/website/venv/local/lib/python2.7/site-packages/twisted/web/server.py", line 184, in process self.render(resrc) File "/home/dean/website/venv/local/lib/python2.7/site-packages/twisted/web/server.py", line 235, in render body = resrc.render(self) --- <exception caught here> --- File "/home/dean/website/venv/local/lib/python2.7/site-packages/scrapyd/webservice.py", line 21, in render return JsonResource.render(self, txrequest).encode('utf-8') File "/home/dean/website/venv/local/lib/python2.7/site-packages/scrapyd/utils.py", line 20, in render r = resource.Resource.render(self, txrequest) File "/home/dean/website/venv/local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render return m(request) File "/home/dean/website/venv/local/lib/python2.7/site-packages/scrapyd/webservice.py", line 49, in render_POST spiders = get_spider_list(project, version=version) File "/home/dean/website/venv/local/lib/python2.7/site-packages/scrapyd/utils.py", line 137, in get_spider_list raise RuntimeError(msg.encode('unicode_escape') if six.PY2 else msg) exceptions.RuntimeError: Traceback (most recent call last):\n File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main\n "__main__", fname, loader, pkg_name)\n File "/usr/lib/python2.7/runpy.py", … -
Converting class object to readable value for get_api_representation function
Previous topic where I was kindly helped by @gasman so i have a model class ingredients like: @register_model_chooser class Ingredient(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name and to represent this in API i created this class: class IngredientChooserBlock(ModelChooserBlock): def get_api_representation(self, value, context=None): if value: return { 'name': value.name, } then i have another model class that uses IngredientChooserBlock class: @register_model_chooser class Menu(models.Model): ingredient = StreamField([ ('zutaten', IngredientChooserBlock('kitchen.Ingredient')) ], null=True, verbose_name='', blank=True) def __str__(self): return self.title and because i need this ingredient in my API i created same model class to overwrite get_api_representation: class WeekChooserBlock(ModelChooserBlock): def get_api_representation(self, value, context=None): if value: return { 'ingredients': value.ingredient, } and in the end in my main model class I'm trying to use this WeekChooserBlock which takes kitchen.Menu as argument like so: class Week(models.Model): dishes_sp = StreamField([ ('menu', WeekChooserBlock('kitchen.Menu')) ], null=True, verbose_name='', blank=True) The problem is that it prints out an error in DRF like this: Object of type 'StreamValue' is not JSON serializable Didn't want to create too big question, but for greater clarity i have actually another objects in my Menu class like: class Menu(models.Model): title = models.CharField(max_length=255) image = models.URLField(blank=True, null=True) price = models.FloatField(blank=True, null=True, max_length=255) ingredient = StreamField([ ('zutaten', IngredientChooserBlock('kitchen.Ingredient')) … -
Different Users: Customer & Producer in two different Django Apps
I´m working on an Django Webpage and need some help regarding my Usermodel. I´ll already have a Login for the both Producer & Customer that looks like this: class LoginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User= ['username', 'password'] fields So iff you open /producer/login or /customer/login you can login with a set name and passwort stored in the mysql DB Now I want to change the login to a kind of global login where you have just one login page that redirects you wether you are a producer or customer. Can anybody help me or give me a hint how i can implent this? I red this article Restricting User access to different apps in Django but wasn´t sure if this is what I need. -
PyCharm specify returned type as static in classmethod
I created my own layer under django.db.models.Model class MainModel(models.Model): @classmethod def getIf(cls, **kwargs): results = cls.objects.filter(**kwargs) if results.count() > 0: return results.first() else: return None class Meta: abstract = True Can I specify for PyCharm autocomplete that I expect the same as cls.objects.filter and return instance of cls? In phpStorm I was typing //** return static */ -
How to properly override User admin in Django
I want to add add inline model and exclude some fields from User change form in Django admin. I'm trying to override Django's built-in UserAdmin to preserve User change design: class UserCustomAdmin(UserAdmin): # list_display = ['id', 'username','email', 'last_login'] exclude = ['groups','user_permissions'] inlines = [UserProfileInline] Even exclude = ['groups'] raises error: u"Key 'groups' not found in 'UserForm'. Choices are: date_joined, email, first_name, is_active, is_staff, is_superuser, last_login, last_name, password, username." How to make it work? -
django delete a case if not answered
I have an open question in django in which the participant can respond giving different ideas. I want to save the answer if something is written in the case; otherwise delete the case. Until now I have: answer={} if question.is answered(participant): answer= question.get contributions(participant) else: question.delete() -
python-social-auth generate 'connect with' link as string
I'm using social-auth-app-django to support logins with social apps. This code is on a angular-djangorest app, so basically the django doesn't serve the html pages. Now from the docs, I can see that if I did serve the html pages, I would simply add the following line to generate the 'connect with' link: <a href="{% url 'social:begin' 'instagram' %}">Login with Instagram</a> but since I don't serve the html myself, I need to supply the angular app the string generated between the {% %} myself. For example def connect_with_instagram(request): . . return HttpResponseRedirect(<the 'connect with' string>) So how can I generate this string? -
Read from text file and display in tabular format based on checkbox selection by user
NEW QUESTION This is data in my text file. I will display the string after I found 'id_' which is the id user. Display the id user in one column. Then, under id user got delay_index_time which I will display next line of the output. But sometimes delay_index result will have more than one result. I will zip it/combined in one table with 2 column. It will display using a check box selection. if let's say user only want to view user id it will only display that. if the user ticks both of it in check box it will display both of it in the table. For the check box, I have no idea on it. Sorry if I'm asking a lot of question :( id_A1 delay_index_time s_7754 s_7731 id_A2 delay_index_time mrs_7745 id_A3 delay_index_time s_77789 id_A4 delay_index_time s_7752 This is my coding in views.py context = {} with open(path) as input_data: for line in input_data: if line.startswith('id_'): if 'output' in context: context['output'].append(line.lstrip('id_').rstrip()) if search_string in line: if 'output1' in context: context['output1'].append(next(input_data).lstrip('s_').rstrip()) context = { 'output': [(line.lstrip('id_').rstrip())], 'output1': [(next(input_data).lstrip('s_').rstrip())] } return render(request, 'Output.html', context) This is my tabular html <div class="container" style=" width:170px;"> <table style="" class="table table-bordered"> <thead class="success" > … -
Enabling CORS on Google App Engine for a Django Application
I have been trying to enable CORS headers on Google app engine but none of the methods that I found over the internet worked for me. My application is on Python/Django and I want my frontend application (which is hosted separately) to be able to make API calls to my backend platform on Google App Engine. The January 2017 release notes say that We are changing the behavior of the Extensible Service Proxy (ESP) to deny cross-origin resource sharing (CORS) requests by default It can be seenhere And the solution to enable CORS given by them is to add the following snippet to the service's OpenAPI configuration. "host": "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog", "x-google-endpoints": [ { "name": "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog", "allowCors": "true" } ], ... So I followed this example and created two files in my code base openapi.yml : swagger: "2.0" info: description: "Google Cloud Endpoints APIs" title: "APIs" version: "1.0.0" host: "echo-api.endpoints.<PROJECT-ID>.cloud.goog" x-google-endpoints: - name: "echo-api.endpoints.<PROJECT-ID>.cloud.goog" allowCors: "true" paths: "/healthcheck": get: description: "Healthcheck for the application" operationId: "Healthcheck for the application" responses: 200: description: "OK" schema: type: string openapi-appengine.yml: swagger: "2.0" info: description: "Google Cloud Endpoints API fo localinsights backend server" title: "Localinsights APIs" version: "1.0.0" host: "<PROJECT-ID>.appspot.com" Then I ran this command: gcloud …