Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add post function in Django detailview
In my application I have four models Question, QuestionComment, Answer, AnswerComment. I want to add Question comment form, Answer form and Answer comment form in my detailview. QuestionComment form and Answer form are working fine in my detail view, but the problem arising in AnswerCommentForm, Here is my code, class DetailView(generic.DetailView): model = Question template_name = 'mechinpy/detail.html' def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) context['answercommentform'] = AnswerComment() context['answerform'] = AnswerForm() context['answercommentform'] = AnswerCommentForm() context['questioncommentform'] = QuestionCommentForm() return context def post(self, request, slug): question = get_object_or_404(Question, slug=slug) if AnswerForm(): form = AnswerForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.question = question answer.user = self.request.user answer.save() return redirect('mechinpy:detail', question.slug) if QuestionCommentForm(): form = QuestionCommentForm(request.POST) if form.is_valid(): questioncomment = form.save(commit=False) questioncomment.user = self.request.user questioncomment.question = question questioncomment.save() return redirect('mechinpy:detail', question.slug) if AnswerCommentForm(): form = AnswerCommentForm(request.POST) answer = get_object_or_404(Answer, pk=pk) #this is where the problem is if form.is_valid(): answercomment = form.save(commit=False) answercomment.user = self.request.user answercomment.answer = answer answercomment.save() return redirect('mechinpy:detail', question.slug) Problem is adding answer to the answercomment.answer, How do I call the answer with its pk, My detailview url, path('m/question/<slug:slug>/', views.DetailView.as_view(), name='detail'), Model for answer and answercomment, class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) answer_text = models.TextField() answered_date … -
Is there a feature in Django for saving a history of files uploaded by a user?
I have built a Django application that allows a user to upload his/her resume. The resume can be of any format(.pdf, .txt and even .mp4 video). The user also has the option to update the current resume by uploading a new file. I wish to have a feature wherein the user has the option to go back to his/her history of uploaded resumes to view the old ones. Django's FileField model object only keeps track of the latest upload. Is there are any existing feature in Django that would help me in easily build a feature wherein a history of uploaded files are maintained? -
Refund issue with paypal using django and python
I'll use django-paypal for processing payments in my site, but, I need the refund funcionality, wich I didnt find in the django-paypal docs. How can I achieve this, if django-paypal doesnt has this featured I'd to move to other package, in that case, any reccommendation? -
Is it possible to plugin data in Javascript via Django?
I actually don't know how to ask this question but here it goes: Here is a script file: <script> window.onload = function () { var chart = new CanvasJS.Chart("line_Sales1", { animationEnabled: true, title: { text: "Sales" }, axisX: { minimum: new Date(Year1, Month, Day), maximum: new Date(Year2, Month, Day), valueFormatString: "MMM YY" }, axisY: { titleFontColor: "#4F81BC", suffix: " POs" }, data: [{ indexLabelFontColor: "darkSlateGray", name: "views", type: "area", yValueFormatString: "#,##0 POs", dataPoints: [ Is it possible to make this portion dynamic by plugging in Django code like:{{ something.getYear() }} { x: new Date(2017, 09, 1), y: 130}, { x: new Date(2017, 10, 1), y: 150}, { x: new Date(2017, 11, 1), y: 175}, { x: new Date(2017, 12, 1), y: 200}, { x: new Date(2018, 01, 1), y: 190}, { x: new Date(2018, 02, 1), y: 150}, { x: new Date(2018, 03, 1), y: 140}, { x: new Date(2018, 04, 1), y: 130}, { x: new Date(2018, 05, 1), y: 120}, { x: new Date(2018, 06, 1), y: 110}, { x: new Date(2018, 07, 1), y: 100}, { x: new Date(2018, 08, 1), y: 115}, { x: new Date(2018, 09, 1), y: 120}, ] }] }); chart.render(); } </script> … -
Trying to develop a web portal that reflects users and scores using django framework
I am trying to develop the scoreboard website which will reflect the users and their respective scores, but i am facing a lot of issues to develop ,since i am new to django framework and python, any help would be appreciated. below the code for the scoreboard which i am getting errors.if someone has come across or developed a scoreboard please help me out with the code. thank you! models.py [root@localhost scoreboard]# cat models.py -- coding: utf-8 -- from future import unicode_literals from auditlog.registry import auditlog from django.db import models Create your models here. class member1(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name + ',' + self.contact_number + ',' + self.yourpost + " , " + str(self.department).upper() class Score(models.Model): granted_by = models.ForeignKey(member1, default=0) granted_to = models.ForeignKey(member1, default=0, related_name="granted_to") class priority(models.Model): link = models.ForeignKey(member1, on_delete=models.CASCADE) score = models.ForeignKey(member1, on_delete=models.CASCADE) name = models.ForeignKey(member1, on_delete=models.CASCADE) def str(self): return str(self.link) + ',' + str(self.number) def alpha_name(self): return str(self.link.name) def score(self): return str(score) member1_choice = [ i.tuple() for i in member1.objects.all() ] consult_choice = [ i.tuple() for i in consultant.objects.all() ] -
Possibility of downloading files from google drive to my desktop from an application without using google sync
I just created an application using google drive API to download files from google drive. Is that possible to download google drive files using google drive API without making a sync with google -
Database schema to map Hotel Amenities from different sources into a uniform format to remove duplicates
I am creating a hotel application that fetches hotel feeds from different sources and store it to database to form a uniform structure and expose API to the mobile application. I am fetching hotels from 3 different sources using python/django app. Now every hotel source has different sets of amenities for example: Source 1 [Expedia] - Free WiFi - Hairdryer In Room - Cable TV - Double Bed - Single Bed - Fireplace Source 2 [SomeHotelProvider] - WiFi - Hairdryer - Television - and so on So here we have same amenity name with different name (Free WiFi and WiFi ) for example. The only problem is that at the Mobile screen it will display two filter [Free WiFi, Wifi] to filter out the result set. So what is best approach to deal with these duplicate values. Need a solution to create a mapping table that maps all duplicates to one amenities master table. Thanks in advance. -
Django inline_formset - ensure at least one item selected
I have an inlineformset_factory which where I need 'result' selected for at least one of the submitted forms: These are my forms: class CBVQuestionForm(forms.ModelForm): class Meta: model = Question fields = ['id','question','image','time','weight','company','tags','category','author'] widgets = {'id': forms.HiddenInput(), 'time' : forms.NumberInput(attrs={'class': 'form-control quiz-search-box'}), 'weight' : forms.NumberInput(attrs={'class': 'form-control quiz-search-box'}), 'company' : forms.HiddenInput(), 'author' : forms.HiddenInput(), 'tags' : TagWidget(attrs={'class':'form-control'}), } def clean_tags(self): data = self.cleaned_data['tags'] for d in data: d = d.replace('[','').replace(']','') return data class AnswerForm(forms.ModelForm): class Meta: model = Answer exclude = ['user_answer'] fields = ['result','question','answer'] widgets = { 'result' : forms.CheckboxInput( attrs = { 'class' : 'right_answer' } ), 'question' : forms.HiddenInput(), 'answer' : forms.Textarea( attrs = { 'class' : 'form-control quiz-search-box', 'required' : '', 'rows' : 3, } ), } AnswerFormSet = forms.inlineformset_factory( Question, Answer, form=AnswerForm, extra=0, can_delete = True, can_order = False, max_num=4, min_num=1 ) I'm forcing the first inline form to have result set to true using JQuery, and then ensuring if another result is selected, again using JQuery to keep it to just one selected, like so: $('#qform').on('change', 'input.right_answer', function() { $('input.right_answer').not(this).prop('checked', false); $(this).prop("checked", "checked"); }); $(document).ready(function() { // set the first check box to checked {% if not edit %} $('#id_answer_set-0-result').prop("checked", "checked") {% endif %} }) The … -
Django Rest Response when data is already in JSON
class Ebay(APIView): #permission_classes = (permissions.IsAuthenticated,) #renderer_classes = (JSONRenderer,) def get(self): search = EbayFind(keywords='phone') result = search.get_results() return Response(result.json()) #return HttpResponse(result.json()) this returns it correctly I have created a simple non-model API endpoint using DRF to return some JSON using results.json() on a requests object. It is again converted into JSON in the Response (giving double backslashes and ruining the JSON), whereas HttpResponse returns it fine. I haven't set any default renderer in settings.py so how could I stop it converting the response to JSON for this endpoint? -
How to Delete the Digital Ocean Space Image from Python Django
Thanks for view the my question, Please let me know any reference or sample code to how to delete the Digital Ocean Space Image from Python Django, There is example for list and upload the image in Space Image. Please help me to find the way for my solution Please refer sample code like this session = boto3.session.Session() client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id='26YTFH4YYWMYYESNRMR2', aws_secret_access_key='HV2ZELOATp6NzNFBk7LbYZrSnG5pcqfZbiZXU0XMRfk') client.delete_file('inspxotestspace', # Name of Space imagename1) # Name for remote file Thanks in advance, Regards, Kishore -
Google cloud endpoints REST API
I have a monolithic web Application in Django and used DB and NDB as model. we would like to migrate this from REST API to Endpoint based API system (Single API for client Applications and Internal Use). Is this possible? But I am not able to find any documentation in AppEngine standard environment. If possible, can we include this new endpoint API in existing Django URL- View Architecture? -
Sentry disable django.security.* Exception
I'm using sentry-python SDK for capture exceptions from my django server. I don't want to capture django.security.DisallowedHost like above. How to remove sentry handling for that exception?? I attached my server configuration below. settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, }, 'loggers': { # Silence SuspiciousOperation.DisallowedHost exception ('Invalid # HTTP_HOST' header messages). Set the handler to 'null' so we don't # get those annoying emails. 'django.security.DisallowedHost': { 'handlers': ['null'], 'propagate': False, }, } } sentry_sdk.init( dsn=os.environ['SENTRY_DSN'], integrations=[DjangoIntegration()], send_default_pii=True, release=f"{os.environ['STAGE']}@{os.environ['VERSION']}", ) -
Can't import custom Middleware whilst using @decorator_from_middleware. (Non Global Middleware)
I was using some custom middleware to check auth of users. This was working great but I don't want to run this middleware on every url. Suggestions point towards using @decorator_from_middleware before each view that you want middleware to run, this would be ideal. Some of my view should be global, others behind auth. I cant seem to import the middleware to call it in the views file. My views.py: from myapp.middleware import * @decorator_from_middleware(AuthCheckMiddleware) def index(request): return render(request, "index.html") My myapp.middleware.authCheck.py: class AuthCheckMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): #CHECK AUTH HERE response = self.get_response(request) return response def process_exception(self, request, exception): return None The error I get: File "/vagrant/myapp/django-project/isadmin/web/views.py", line 93, in <module> @decorator_from_middleware(AuthCheckMiddleware) NameError: name 'AuthCheckMiddleware' is not defined -
Testing jwt authentication using djnago testing or django rest framework testing.
the below code is the function for jwt authentication . this function takes the username and password as its parameter and gives us the jwt token and it also stores the required data in payload. views.py @csrf_exempt @api_view(['POST']) @permission_classes([AllowAny, ]) def authenticate_user(request): try: username = request.data['username'] password = request.data['password'] user = authenticate(request, username=username, password=password) print("meh2") if user is not None: try: payload = jwt_payload_handler(user) token = jwt.encode(payload, settings.SECRET_KEY) user_details = {} user_details['user_id'] = user.id user_details['email'] = user.email user_details['first_name'] = user.first_name user_details['second_name'] = user.last_name user_details['token'] = token role = UserPermission.objects.get(user_id=user.id) user_details['role'] = role.emp_role.role_name if user_details['role'] == 'Student': student_obj = Student.objects.get(user_id=user.id) grade_id = student_obj.grade_id grade_chapter_list = [] user_details['grade_id'] = grade_id chap_obj = Chapter.objects.filter(grade_id=grade_id) for i in chap_obj: sub = {} sub['grade_id'] = i.grade_id sub['grade'] = i.grade.grade sub['subject_id'] = i.subject_id sub['subject_name'] = i.subject.subject_name sub['section_id'] = student_obj.section_id sub['section_name'] = student_obj.section.section_name sub['branch_id'] = student_obj.branch_id sub['branch_name'] = student_obj.branch.branch_name grade_chapter_list.append(sub) user_details['grdsub'] = grade_chapter_list elif user_details['role'] == 'Teacher': dum = SchoolStaff.objects.get(user_id=user.id) all_sub = dum.subjects.all() sub = [] for subject in all_sub: sub.append({"name":subject.subject_name, "id": subject.id}) user_details['subjects'] = sub all_map = dum.mappings.all() mappi = [] for i in all_map: dict = {} dict["grade_id"] = i.grade_id dict["grade_name"] = i.grade.grade dict["branch_id"] = i.branch_id dict["branch_name"] = i.branch.branch_name dict["section_id"] = i.section_id dict["section_name"] = i.section.section_name … -
Keycloak Custom Automatic User Attributes
Im using Keycloak in a somewhat unconventional way (I think). I want a user to be able to register on the Keycloak register page and have that user synced to a LDAP server for authentication against a git server running CentOS. When i register a user, this user is indeed synced to the LDAP server. However, it lacks several attributes to be able to authenticate against the git server, namely: UID, GID, Objectclass: posixAccount, loginShell: /bin/bash, homeDirectory: /home/user I have tried creating default groups and roles with attributes, but this doesnt work, the synced user on the LDAP server does not inherit any of these attributes. I think it has to be hardcoded in somewhere or could it be added with mappers? -
How to create with a ListField of Nested Serializer by using POSTMAN
I have 2 serializers: class SinglePhotoSerializer(ModelSerializer): image = ImageField(max_length=5242880, allow_empty_file=False, use_url=False) class Meta: model = Photo fields = [ 'image', 'caption', ] class PhotoCreateSerializer(ModelSerializer): images = ListField(min_length=1, max_length=10, child=SinglePhotoSerializer()) class Meta: model = Photo fields = [ 'images', 'user' ] This is my viewset: class PhotoComposerView(CreateAPIView): queryset = Photo.objects.all() serializer_class = PhotoComposerSerializer What I create using POSTMAN: As you see, this request by POSTMAN is not validated. Am I wrong in my serializers or POSTMAN request? -
Django forms not displayed in bootstrap 4 modal
recently i'd try to migrate my todo-list app from bootstrap 3 to 4 (4.1.3 exactly) but all my forms disappeared from my modals (a form for create and another for edit). Here is one of my modal with form working with Bootstrap 3 and here is my modal with no form displayed with Bootstrap 4. How can I display forms in modals again ? Here is my sample of code for my create form... Thank you for the help views.py from django.views import generic from tasks.forms import CreateTaskForm from .models import Task class IndexView(generic.TemplateView): template_name = 'tasks/index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data() context['task_list'] = Task.objects.all() return context ... ... class TaskCreateView(SuperuserRequiredMixin, generic.FormView): template_name = 'tasks/create_task_modal.html' form_class = CreateTaskForm model = Task def get_form_kwargs(self): kwargs = super(TaskCreateView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): (status, msg) = form.execute() return HttpResponseRedirect(reverse('tasks:index')) def form_invalid(self, form): return HttpResponseRedirect(reverse('tasks:index')) forms.py from django import forms from tasks.models import Task, Comment from django.core.validators import MinValueValidator from multiselectfield import MultiSelectFormField class CreateTaskForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(CreateTaskForm, self).__init__(*args, **kwargs) LOCATION_CHOICES = ( ... ) CRITICITY_CHOICES = ( ... ) TYPE_CHOICES = ( ... ) STATUS_CHOICES = ( ... ) ENVIRONMENT_CHOICES = … -
how to implement auto logout using python-django on browser close
I have a use case where I want the user to get logged out when they close their browser. And next time when the user visit the website,user should be rdirected to landing page/login page of my application. From my side, I have implemented the following in djnago setting.py file: SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 40 SESSION_SAVE_EVERY_REQUEST = True LOGOUT_REDIRECT_URL = '/logout_user/' But this not helping. Any idea how to achieve this scenario? Any suggestions would be helpful. Thank you in advance. -
Zoom the region of PDF to select the required region on it using python
I'm working on a project where I need to select a region using my mouse to retrieve the data in that region .I'm using pdf-query (python library) but the result produced by it contain the data which is near to my selected region as well , So I wish to zoom the region of the pdf where the mouse cursor is moved so that I can select exactly the place which I want to select. Is there any option to carry out this process ? -
Why does Celery only recognize tasks from single Django app
So we have this Django project with multiple apps, and we use celery for tasks. The issue we are running into is that only the tasks inside the tasks.py of a single app will run, other tasks.py tasks in other apps return the following error: celery_1 | [2018-10-22 08:27:59,563: ERROR/MainProcess] Received unregistered task of type 'biko.supplier.tasks.test_task'. celery_1 | The message has been ignored and discarded. celery_1 | celery_1 | Did you remember to import the module containing this task? celery_1 | Or maybe you're using relative imports? celery_1 | celery_1 | Please see celery_1 | http://docs.celeryq.org/en/latest/internals/protocol.html celery_1 | for more information. celery_1 | celery_1 | The full contents of the message body was: celery_1 | b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) celery_1 | Traceback (most recent call last): celery_1 | File "/usr/local/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 557, in on_task_received celery_1 | strategy = strategies[type_] celery_1 | KeyError: 'biko.supplier.tasks.test_task' This happens when I run test_task.delay() Here is the supplier tasks.py: from config.celery import app @app.task(shared=True) def test_task(): print("Runnign this task correctly") Here is the a part of the shop tasks.py, where the tasks do work correctly: from django.contrib.contenttypes.models import ContentType from config.celery import app from celery_once import QueueOnce from … -
Error connecting Django to MSSQL Server 2012
Am getting an error in making magrations for my current django project. below is the code written in settings.py file to connect to MSSQL Server. DATABASES = { 'default': { 'ENGINE':'sql_server.pyodbc', 'NAME':'JTPROD', 'HOST':'TZACL5X8H1N2\SQLEXPRESS', ##this is my local machine database 'USER':'xxx', ##ommitted for the post 'PASSWORD':'xxx',##ommitted for tht post 'PORT':'', 'OPTIONS':{ 'provider': 'SQLOLEDB', # Have also tried 'SQLCLI11' and 'SQLCLI10' 'extra_params': 'DataTypeCompatibility=80', 'driver':'SQL Server', }, }, } but am getting the following error when I run "python manage.py migrate Traceback (most recent call last): File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sql_server\pyodbc\base.py", line 307, in get_new_connection timeout=timeout) pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\elukamis\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\migrate.py", line 82, in handle executor … -
Django doesn't save PATCH request to database
I am trying to PATCH an object in my database via the Django REST Framework. The request gets handled in my backend and the updated attribute is part of the response I receive. But: the attribute is not updated in the database. Or, at least it does not show in the Django Admin. What am I missing here? I am using the following Django REST framework setup: DefaultRouter router = DefaultRouter() router.register(r'relationships', relationship_views.RelationshipViewSet) ModelViewSet class RelationshipViewSet(viewsets.ModelViewSet): queryset = Relationship.objects.all() serializer_class = RelationshipSerializer def get_queryset(self): return Relationship.objects.filter(from_user=self.request.user) ModelSerializer class RelationshipSerializer(serializers.ModelSerializer): from_user = AccountSerializer(read_only=True) to_user = AccountSerializer(read_only=True) class Meta: model = Relationship fields = '__all__' -
Django connection with an Auto-rotate password DB
I have a Django application that is working perfectly. It's connected to a MySQL server hosted on the cloud. The MySQL server is set to auto-rotate the password every 30 days for security reasons. Django can access the new password only when settings.py is loaded using a custom function I have developed (that will fetch the new password from AWS Secrets Manager). I'm looking for a way to allow Django to detect if a connection has a problem then update the password all transparent to the user. -
How to give staff access to newly created User In Django
I am new to Djnago and Python. I created middleware class in Djnago with the name StaffAccessMiddleware I used social_django app to create user from Gmail and i want to implement is_staff = True and assign at least one group only if users login in DJango firstTime . My question is how to access user in middleware and check only first time user will enter in this code in that case i need to assign is_staff = True and assign group once user is created. I tried to create middle ware class like below. class StaffAccessMiddleware(object): def process_request(self, request): if hasattr(request, 'user') and request.user.is_authenticated(): user = request.user if groups: groups[0].name return None -
Converting an object into a Queryset
I have two functions def xyz(obj): obj_queryset = Sample.objects.filter(id=obj.id) callfunction(obj_queryset) def callfunction(obj_queryset): """ Do operations """ I need it as a queryset for certain reasons. Is there any way to turn obj into a queryset without doing a database query.