Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing extra data passed while calling a celery task
I have task that I'm starting with apply_async such that I can pass extra data. However I'm having trouble accessing this data in the celery signals. For instance this an example of the task, how I'm calling it and task_prerun signal. @task def export_olx(user_id, course_id, language): pass export_olx.apply_async(args=(user_id, course_id, language), kwargs={'some_key':'some_value'}) @task_prerun.connect(sender=export_olx) def export_olx_prerun(sender, **kwargs): pass Inside my task_prerun signal I'm able to access the args using sender.request.args, however when I try using sender.request.kwargs I get an empty dictionary instead of the extra data I passed {'some_key':'some_value'} Any help on how I can access this data will be much appreciated thank you. -
Cant get FCM push notifications from my server on iOS (working on Android)
New to iOS/Swift and cant get push notifications working. I have configured my server backend to push notifications to my app when some action happens. I have configured a data notification trough FCM because I need some custom data in the notification to open one activity/view or another. This is the code used to send the notification (python/django): registration_id = profiletarget.device_token message_title = "Ha llegado tu turno" message_body = "Entra y escribe en el relato para el que estás en cola" data_message = { "title" : "¿Listo para escribir?", "body" : "Ha llegado tu turno para escribir en el relato. Recuerda que tienes un minuto para aceptar tu turno y 3 para escribir.", "bookid" : booktarget.pk, "multimediaurl" : multimediaused.url } result = push_service.notify_single_device(registration_id=registration_id, data_message=data_message) Everything inside this code is working, because I get them correctly on Android. But on iOS... I can't get it working. I have get the notifications token, I have post it to my server, I have use the notification sender on FCM console to send test push notifications (the iphone get them), but not the ones from my custom method, It doesn't show anything. Is anything wrong in the server method or am I missing something? … -
Why generated project.css is not in .gitignore and how to properly solve it?
I generated a project from cookiecutter-django with enabled options: Docker and Gulp. So there is Gulpfile.js, which compiles file sass/project.scss to css/project.css and then minifies it to css/project.min.css. The link to the latter is in HTML. But this min file and generated CSS are not included in .gitignore. The same thing with js (*.min.js is not ignored). I added *.min.js and *.min.css to .gitignore. But what I should do with css/project.css, maybe I should ignore the CSS folder entirely, since I'm using sass? What are the proper solutions in this case? -
Need help submitting form data without using forms.py
I started learning django few days ago. I'm currently working on a django form inside Bootstrap modal and I can't seem to submit my form data to the database. Can tell me what is the issue? Btw, I'm not using django forms.py. index.html <div class="modal-content"> <form action="" method="POST"> {% csrf_token %} <div class="modal-header"> urls.py from django.urls import path from . import views app_name = 'aclapp' urlpatterns = [ path('', views.index, name='index'), path('aclapp/', views.index, name='index'), path('submit/', views.submit, name='submit'), ] views.py def submit(request): if (request.method == 'POST'): name = request.POST['name'] user_id = request.POST['user_id'] email = request.POST['email'] section = request.POST['section'] status = request.POST['status'] roles = request.POST['roles'] user = UserDetail(name=name, user_id=user_id, email=email, section=section, status=status, roles=roles) user.save() return redirect('/index.html') else: return redirect('/index.html') Here's my GitHub project files: https://github.com/josephsim/django-access-control-list -
Celery for Testing Configuration in Django
I have a file celery_test.py which should load the configuration settings for testing(config.test) in Django but instead it loads configuration of Development(config.development) from __future__ import absolute_import import os from django.conf import settings from celery import Celery os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "config.testing" ) test_app = Celery('test') test_app.config_from_object('django.conf:settings') test_app.autodiscover_tasks() print("Testing celery") print(settings) @test_app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) When i am printing settings it it printing config.development insteas of config.testing. Can anyone help me here how to load config.testing. -
How do i create pagination in filter object
I have a category men_clothing_shirt, i want to add pagination to the template page. I tried this and it does not work for me. def men_shirt(request): queryset_list =Category.objects.filter(name='man_clothing_shirt') paginator = Paginator(queryset_list, 1) page = request.GET.get('page') try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) context = { 'menshirtpaginator': queryset, } return render(request,'men_shirt.html', context) -
Can I use js-cookie to remamber the sidebar status
As title I wanna save the sidebar status with js-cookie can anyone tell me how to do this? thanks and regards -
Chart js in Django not work only output JSON file
I’m using Django-Chartjs 1.5.0 ( https://pypi.org/project/django-chartjs/ ) in my Django file but out bout appear only JSON file only like thisenter image description here I need it to appear like this CHART ERROR my cod in github link https://github.com/ahmed-solyman/cost this is my cod view js class LineChartJSONView(BaseLineChartView): def get_labels(self): “”“Return 7 labels for the x-axis.”"" return [“January”, “February”, “March”, “April”, “May”, “June”, “July”] def get_providers(self): “”“Return names of datasets.”"" return [“Central”, “Eastside”, “Westside”] def get_data(self): “”“Return 3 datasets to plot.”"" return [[75, 44, 92, 11, 44, 95, 35], [41, 92, 18, 3, 73, 87, 92], [87, 21, 94, 3, 90, 13, 65]] line_chart = TemplateView.as_view(template_name=‘line_chart.html’) line_chart_json = LineChartJSONView.as_view() -
How to compute the total average of per students using Javascript
I hope my title is enough to understand my question, ive been post this question several times but I hope this time I get help. <table id="blacklistgrid" border="2px"> <tr> th id="th">Students Name</th> </tr> {% for student in teacherStudents %} <tr class="tr2"> <td id="td">{{ student.Students_Enrollment_Records.Student_Users }}</td> </tr> {% endfor %} </tr> </table> <button type="button" value="" class="save" onclick="doTheInsert()" title="Insert New Cell" id="save">&plus;&nbsp;Insert New Cell</button> <button type="button" value="" class="save" onclick="undoTheInsert()" title="Undo Recent Action" id="unsave">&times;&nbsp;Undo Recent Action</button> <button type="button" value="" class="save" onclick="compute()" title="Undo Recent Action" id="compute">Compute</button> this is my script for the button Insert Cell <script> var counter = 0; function doTheInsert(){ let header=$("tr#tr"); // same as $.find("tr[id='tr2']") $('#th').after("<th data-id='headers' id='header'><input type='date'></th>"); let rows=$(".tr2"); rows.append("<td data-id='row' ><input type='number' class='average'/></td>"); counter++; } </script> and this is the script for the computation <script> function compute(){ var sum = 0; var rows = document.getElementsByClassName("average"); for(var i = 0; i < counter; i++){ sum += parseInt(rows[i].value); } var average = sum / counter; document.getElementById("demo").innerHTML = average; let header=$("tr#tr"); // same as $.find("tr[id='tr2']") $('#thb').before("<th data-id='headers' id='headerss'>Average</th>"); } </script> this is my current script in computation <script> function compute(){ var sum = 0; var rows = document.getElementsByClassName("average"); for(var i = 0; i < counter; i++){ sum += parseInt(rows[i].value); } var … -
How do I get started with open source contribution?
Hi I'm looking to contribute to an open source project. I like python and I want to contribute to python Django open source. I tried to go to the ticket section and look to fix bugs but I don't understand most problems due to my lack of knowledge. Should I read some books on the django framework? Like how it's written and its philosophies? I seem to only find books on how to use Django but not on how it's built or written. Any suggestions? -
How to send data from Django to React?
I want to create a project using Django(backend) and React.js with Redux(frontend). In this project, ı want to do the operations on the django side and send the react application whenever the result of the process occurs. What is the best way to send data? Thanks. -
Поле по умолчанию при создании объекта в Django Rest Framework
A request to create an object through POST, when the request is executed, an object is created, but the ManyToManyField field is not automatically set in the line device.status.set ([1]). an error "" should be issued for the "id" field before this many-to-many relationship can be used. please tell me how can I fix it? class DevicePUT(APIView): queryset = Device.objects.all() serializer_class = DeviceSerializer def post(self, request, *args, **kwargs): serializer = DeviceSerializer(data=request.data) device = Device() if serializer.is_valid(): question = serializer.save() serializer = DeviceSerializer(question) device.status.set([1]) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Unable to login by using LinkidIn social login
I am trying to login using social logins like google,github,facebook but when i am trying that in case of LinkedIn i am getting the following error HTTPError at /social/linkedin_login/ HTTP Error 404: Not Found I am user v2 for linkedin views.py required_info = "id,first-name,last-name,email-address,location,positions,educations,industry,summary,public-profile-url,picture-urls::(original)" rty = "https://api.linkedin.com/v2/me:(" + required_info + ")" + \ "?format=json&oauth2_access_token=" rty += accesstoken details = ur.urlopen(rty).read().decode('utf8') I am getting error in details = ur.urlopen(rty).read().decode('utf8') else: rty = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=" + \ settings.LN_API_KEY rty += "&scope=r_liteprofile r_emailaddress w_member_social&state=8897239179ramya" rty += "&redirect_uri=" + request.scheme + '://' + \ request.META['HTTP_HOST'] + reverse('social:linkedin_login') return HttpResponseRedirect(rty) Can someone help me out of this error. -
Django - React production Deployment Using Apache | Either React or Django Working
I'm trying to run Django and React app together on Digital Ocean Server using apache2. I am facing an issue on adding WSGIScriptAlias If, I am adding WSGIScriptAlias then django API working fine but react stopped working. WSGIScriptAlias / /proProjects/Portal/ApprovalSystem/wsgi.py else, If, I remove WSGIScriptAlias then react app is working fine. This is my syntax for wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ApprovalSystem.settings") application = get_wsgi_application() Please help? -
Cannot update user profile information
I have been trying to create a form that would allow a user to edit some of the information saved in their profile. The problem I am having currently is that when a user fills in the form and saves it, the information in their profile is not updated based on the values they filled in. I have tried reading through the documentation on forms in Django but still struggling to figure this out. This is the code i have in forms.py: #mentor sign up form class TeacherSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) linkedin = forms.URLField(max_length=200) class Meta(UserCreationForm.Meta): model = User fields = ('email', 'username', 'first_name', 'last_name') def save(self, commit=True): self.instance.is_teacher = True user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() mentor = Mentor.objects.create( user=user, linkedin=self.cleaned_data['linkedin'] ) return user # edit mentor profile class MentorProfileForm(forms.Form): class Meta(TeacherSignUpForm.Meta): model = User exclude = ('password') models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) ... class Mentor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) linkedin = models.URLField(max_length=200,null=True,blank=True) photo = models.ImageField(null=True,blank=True) def __str__(self): return "Profile of user {}".format(self.user.username) @receiver(post_save,sender=User) def create_or_update(sender, instance,created, **kwargs): if created: Mentor.objects.get_or_create(user=instance) post_save.connect(create_or_update, sender=User) teachers.py - this is the equivalent of views.py - … -
Could not install packages due to an EnvironmentError: 404 Client Error
How to resolve the above error? -
Database Allow Duplicate Entry for Foreign Key in Django
I want to allow date duplicate entry for foreign keys. Is there any method in Django I can do it? your help will be highly appreciated. Thank you. Eg: I have a user "X" and "Y" and I want to store work status such as (my work entry time, my work exit time) but on the same date it can done only once by both the user. models.py class TimesheetDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="timesheet",null="True") date = models.DateField(max_length = 10,unique=True) day = models.CharField(max_length = 10) startTime = models.CharField(max_length =10) endTime = models.CharField(max_length =10) breakTime = models.CharField(max_length=3) normalTime = models.FloatField(max_length=10) overTime = models.FloatField(max_length = 10) holidayTime = models.FloatField(max_length = 10) weekType = models.CharField( max_length = 10) attendance = models.CharField( max_length = 10) content = models.TextField( max_length = 300) -
Django finding the path of the file problem
skin -mysite -myapp -templates -index.html -mysite -urls.py -admin.py -views.py I create the virtual environment in ~/home/env and the index.html is located in /home/jake/Gits/skin/mysite/myapp/templates/index.html views.py from django.shortcuts import render, render_to_response # Create your views here. def index(request): return render_to_response('index.html') url.py from django.conf.urls import include, url from django.contrib import admin from myapp import views as v urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', v.index), ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> </html> and the this Django project did not find the right path TemplateDoesNotExist at / index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.8.1 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: /home/jake/Gits/skin/mysite/myapp/views.py in index, line 6 Python Executable: /home/jake/Gits/skin/bin/python Python Version: 3.7.3 Python Path: ['/home/jake/Gits/skin/mysite', '/home/jake/Gits/skin/lib/python37.zip', '/home/jake/Gits/skin/lib/python3.7', '/home/jake/Gits/skin/lib/python3.7/lib-dynload', '/home/jake/anaconda3/lib/python3.7', '/home/jake/Gits/skin/lib/python3.7/site-packages'] Server time: Wed, 8 Jan 2020 06:47:32 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: Using loader django.template.loaders.app_directories.Loader: /home/jake/Gits/skin/lib/python3.7/site-packages/django/contrib/admin/templates/index.html (File does not exist) /home/jake/Gits/skin/lib/python3.7/site-packages/django/contrib/auth/templates/index.html (File does not exist) Traceback Switch to copy-and-paste view /home/jake/Gits/skin/mysite/myapp/views.py in index return render_to_response('index.html') ... ▶ Local vars -
How to create password in django rest framework
Creating user using django rest framework, how to encrypt the user password.Need help with that. here is my view class UserCreateAPIView(generics.CreateAPIView): def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): User( serializer.save() ) return Response({"status":"sucess", "code":status.HTTP_201_CREATED, "details":serializer.data}) return Response({"status":"unsuccessful", "code":status.HTTP_400_BAD_REQUEST, "detsils":serializer.errors}) -
Django Deploy to AWS EB Show 500 Internal Server Error
I am just trying to deploy a sample Django app to AWS EB. I do the exact same with this tutorial=> Deploy Django on AWS But the result is not the same. I got this error message and May I know how to fix this issue? -
how to correctly call the function in readview in django
I created a piece of code that is called in several places, so I decided to create a separate function from it, but I have a big problem how to call it in a generic view. This is my views.py def subscribe(request, pk): if request.POST.get('action') == 'post': project = Project.objects.get(pk=pk) obj = Profile.objects.get(user=request.user) obj.projects.add(project.id) obj.save() data = {'is_valid': True, 'project': str(project)} return JsonResponse(data) class ProjectReadView(BSModalReadView): model = Project template_name = 'projects/project_shortcut.html' def (self, project_id, **kwargs): subscribe(self.request, project_id) -
i am not able to create project using django in command prompt. I have also tried setting up Environment Variable
i am not able to create project using django in command prompt. I have also tried setting up Environment Variable -
django - re-running migration that creates constraints and fails halfway
I have a migration that adds a bunch of unique_together constraints. When I execute it, it fails halfway because some tables don't respect this constraint. So I have to go in and fix the data, and then run the migration again. Problem is that when I try to run it again, it complains that the constraints already exist django.db.utils.IntegrityError: (1062, "Duplicate entry '406-14933' for key 'app_model_language_id_category_id_29dac763_uniq'") This happens in tables in which there was no problem in the previous run, hence the constraint was created. Then I have to go in and delete the constraint by hand, and then I can run it again. Is there a way to just let it ignore this error and continue? -
Angular recieves Html instead of JSON from Django Server's Response
Scenario: Running my angular8 code which involves http.get using ng serve Running django Rest Service, which return Response({"product":["mac","alienware"]"} (or) return JsonResponse({"product":["mac","alienware"]"} It works fine in the front end. But when working in my VM, Using Nginx, where the root points the static files built by ng build and the /api/ refers to the proxy_pass of the websocket of Gunicorn binded It returns a html file(The index file) as response when printed and throws error, Json cannot parse because of "<" at position 0. The request header has "Content-Type": "application/json;",Accept: "application/json", What solution can be applied? -
Tkinter code for popup window display on my current page but it is shows icon on taskbar while im cliking that then on
This is my django adminpage I'm going to choose add or delete rules in client then I click go that will display a tkinter popup window display on my current page but it is shows icon on taskbar while I'm cliking that then only it display window class ArticleAdmin(admin.ModelAdmin): list_display = ['rule_id','item_typ', 'rule_desc'] actions = ['create_rule_client_relation', 'delete_rule_client_relation'] search_fields = ['item_typ'] def get_actions(self, request): actions = super().get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] return actions def create_rule_client_relation(self, request, queryset): root = tk.Tk() root.title("Hey Buddy") mainframe = Frame(root) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) mainframe.pack(pady=100, padx=100) # tkvar = StringVar(root) tkvar = StringVar(root) client_list = client_informatn.objects.all().values_list('client_name',flat=True) tkvar.set(client_list[0]) popupMenu = OptionMenu(mainframe, tkvar, *client_list) Label(mainframe, text="Choose a client").grid(row=1, column=1) popupMenu.grid(row=2, column=1) def change_dropdown(*args): global client_name client_name = tkvar.get() root.destroy() button = Button(root, text="OK", command=change_dropdown) button.pack() root.mainloop() client_id = client_informatn.objects.filter(client_name=client_name).values_list('client_id', flat=True)[0] rows_updated = 0 row_already_found = 0 for rule_id in queryset.values_list('rule_id', flat=True): if not crt_rule_client_relation.objects.filter(client_id=client_id, rule_id = rule_id).exists(): crt_rule_client_relation.objects.create(rule_id=rule_id, client_id=client_id) rows_updated += 1 else: row_already_found += 1 if rows_updated == 1: message_bit = "1 rule was" else: message_bit = "%s rule were" % rows_updated if row_already_found == 0: self.message_user(request, "%s successfully added to the client." % message_bit) else: self.message_user(request, "{message_bit} successfully …