Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding an Export Format for files in Django Admin
Helloo, I have added the ImportExportActionModelAdmin function in my Admin for Project, but I can not find the option to choose the format of the file to download and option to export orders. How do I add that option to download features? Here is the admin.py def order_pdf(obj): return mark_safe('<a href="{}">PDF</a>'.format(reverse('core:admin_order_pdf', args=[obj.id]))) order_pdf.short_description = 'Order PDF' class OrderAdmin(ImportExportActionModelAdmin): list_display = ['id', ....., order_pdf] -
I am trying to install mysql using pip install mysql-python command and getting error
Running setup.py install for mysql-python ... error ERROR: Command errored out with exit status 1: command: 'c:\users\pkhar\pycharmprojects\socialmedia\venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\pkhar\\AppData\\Local\\Temp\\pip-install-uzolldq5\\mysql-python\\setup.py'"'"'; file='"'"'C:\Users\pkhar\AppData\Local\Temp\pip-install-uzolldq5\mysql-python\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(cod e, file, '"'"'exec'"'"'))' install --record 'C:\Users\pkhar\AppData\Local\Temp\pip-record-ani9ddry\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\pkhar\pycharmprojects\socialmedia\ven v\include\site\python3.7\mysql-python' cwd: C:\Users\pkhar\AppData\Local\Temp\pip-install-uzolldq5\mysql-python Complete output (24 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.7 copying mysql_exceptions.py -> build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\MySQLdb copying MySQLdb_init.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.7\MySQLdb creating build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.7\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\pkhar\pycharmprojects\socialmedia\venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\pkhar\AppData\Local\Temp\pip-install-uzolld q5\mysql-python\setup.py'"'"'; file='"'"'C:\Users\pkhar\AppData\Local\Temp\pip-install-uzolldq5\mysql-python\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n '"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\pkhar\AppData\Local\Temp\pip-record-ani9ddry\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\pkhar\pycharmprojects\socialmedia\venv\include\site\python3.7\mysql-python' Check the logs for full command output. Can someone help me in installing mysql client -
Create object automatically after saving another object
I have a car heading towards a series of possible, predefined locations. class locations(models.Model): name = models.CharField(max_length=30, blank=True) coordinates = models.CharField(max_length=30, blank=True) def __str__(self): return self.name In this example, the objects created are New York, Ohio, and Wyoming. Then I have a type of car with the following attributes: class cars(models.Model): type = models.CharField(max_length=30, blank=True) MaxRange = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000')) Speed = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000')) def __str__(self): return self.type When the car departs, that is tracked by another table with values pertaining to when the car could arrive at locations given by the model, locations. class departure(models.Model): car_name = models.ForeignKey(cars, null=True, on_delete=models.CASCADE) location_name = models.CharField(max_length=30, null=True, blank=True) range_or_not = models.CharField(max_length=30, null=True, blank=True) arrival_time = models.CharField(max_length=30, null=True, blank=True) def save(self, *args, **kwargs): for loc in location.objects.all(): self.location_name = #calculation self.range_or_not = #calculation self.arrival_time = #calculation super(departure, self).save(*args, **kwargs) def __str__(self): return self.location_name When the user selects a group and creates a departure, I want to loop through all the locations and generate calculated values pertaining to each of those locations such as: the possible arrival time of a car for all locations inputed in the locations model. I'm not sure how to automatically create a new departure object for … -
Populating a model field based on another model field from a different model
I'm trying to populate "balance" in Transaction model based on "beginning_balance" in the Accounts model, but I'm getting the following error message: save() missing 2 required positional arguments: 'request' and 'pk' What am I doing wrong. Thank you. models.py from django.db import models class Accounts(models.Model): account_nickname = models.CharField(max_length=15, unique=True) beginning_balance = models.DecimalField(max_digits=12, decimal_places=2) def __str__(self): return self.account_nickname class Transaction(models.Model): transaction_date = models.DateField() account_nickname = models.ForeignKey(Accounts, on_delete=models.CASCADE) amount = models.FloatField() balance = models.FloatField(null=True, blank=True, editable=False) def save(self, request, pk): get_beginning_balance = Accounts.objects.get(id=pk) self.balance = get_beginning_balance super().save(request, pk, *args, **kwargs) def __str__(self): return self.account_nickname -
django User update_fields not showing up in signal
i am using django signal to create a user profile automatically when the user is created , and it is work fine , but i want to check also if the user trying to update his "username or email or ..... etc ." i am trying to check these values in signal , but always the 'update_fields' value is None ! 'as you can see in the block of code below ' # create profile automatically when the user is created using (signal) ## def create_profile(sender , **kwargs): if kwargs['created']: Profile.objects.create(PRF_user=kwargs['instance']) if kwargs['update_fields']: print ('some table are updated this is a test') print('all kwargs') print(kwargs) print('end kwargs') #done create profile automatically ## post_save.connect(create_profile , sender=User) enter image description here outprint all kwargs {'signal': <django.db.models.signals.ModelSignal object at 0x00000000037D2780>, 'instance': <User: khder_admin@local.com>, 'created': False, 'update_fields': No ne, 'raw': False, 'using': 'default'} end kwargs how can i tell django to populate 'update_fields' values and send it by signal to my function!? . -
Django modelformset is not validating when trying to update
In my project i am working with modelformsets to create many instances as needed once, when creating those instances modelformsets work like a charm but when i try to update those instances it returns the next error: [{'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {}] This error appears the same times as the length of the instances i am trying to update. Searching through the documentation i found out that when rendering manually my forms, i needed to render the form id's hidden input, i already did that and did not fixed the problem. I would leave my views and forms below: Views //Add Patient View def add_patient(request): if request.method == 'POST': patient_form = PatientForm(request.POST) allergies_form = AllergiesInformationFormset(request.POST) antecedents_form = AntecedentFormset(request.POST) insurance_form = InsuranceInformationForm(request.POST) if patient_form.is_valid() and allergies_form.is_valid() and antecedents_form.is_valid() and insurance_form.is_valid(): patient = patient_form.save(commit=False) allergies_instances = allergies_form.save(commit=False) antecedents_instances = antecedents_form.save(commit=False) insurance = insurance_form.save(commit=False) patient.created_by = request.user patient.save() for allergy_form in allergies_instances: if allergy_form in allergies_form.deleted_objects: allergy_form.delete() else: allergy_form.patient = patient allergy_form.save() for antecedent_form in antecedents_instances: if antecedent_form in antecedents_form.deleted_objects: antecedent_form.delete() else: antecedent_form.patient = patient antecedent_form.save() insurance.patient = patient … -
How to serialize part of a new model based on the user that is logged in (in Django REST framework)
I'm creating a cloud file manager application targeted towards businesses, the project's github is here. I have a Profile model, which is a simple extension of the User model in django.contrib.auth.models by using a OneToOne field as described here. And my use case is that, as a superuser, I should be able to create a profile and assign it to any existing company. But on the other hand, if I'm not a superuser but I am in the "Company Administrator" Group I should only be able to create and edit profiles that belong to my own company. I learned how to used different serializers based on the request in the ViewSet part of the program: class ProfileViewSet(viewsets.ModelViewSet): serializer_class = ProfileSerializer permission_classes = [IsAdminOrCompanyAdmin] def get_queryset(self): u = self.request.user if u.is_superuser: return Profile.objects.all() return Profile.objects.filter(company=u.profile.company) def get_serializer_class(self): if self.request.user.is_staff: return ProfileSerializer return CompanyAdminProfileSerializer But when it comes to the serializer itself, I have no idea how to make it so my company data gets filled in with the company from the request's user: class CompanyAdminProfileSerializer(ProfileSerializer): class Meta: model = Profile fields = ['url', 'user', 'cpf', 'phone_number'] def create(self, validated_data): validated_data['company'] = # ??? # request.user.profile.company would be nice, but I can't … -
Atrribute Error in Django web application
I have been trying this for some days now with no solution.I am getting this weird error after which I have made several trials all of which hasn't solved my issue, I would be glad to receive a solution. ERROR LOGS Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\views\generic\list.py", line 142, in get self.object_list = self.get_queryset() File "C:\Users\Habib\Documents\django\django-new\student-management-system\student_management_app\StaffViews.py", line 364, in get_queryset queryset = self.request.user.quizzes \ File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\utils\functional.py", line 225, in inner return func(self._wrapped, *args) Exception Type: AttributeError at /staff_quiz_home/ Exception Value: 'CustomUser' object has no attribute 'quizzes' MODELS.PY class CustomUser(AbstractUser): user_type_data = ((1, "HOD"), (2, "Staff"), (3, "Student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Quiz(models.Model): owner = models.ForeignKey(Staffs, on_delete=models.CASCADE, related_name='quizzes') name = models.CharField(max_length=255) subject = models.ForeignKey(Subjects, on_delete=models.CASCADE, related_name='quizzes') class student(models.Model): name = models.CharField(max_length=255) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) gender = models.CharField(max_length=50) quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') class Staffs(models.Model): name = models.CharField(max_length=255) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) address = models.TextField() … -
How to link CSS file to pdf.html file for Django
My PDF.html is not linking to any CSS file, I have tried the following: Template PDF.HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href='{% static "css/bootstrap.min.css" %}' rel="stylesheet"> <!-- Material Design Bootstrap --> <link href='{% static "css/mdb.min.css" %}' rel="stylesheet"> <!-- Your custom styles (optional) --> <link href='{% static "css/style.min.css" %}' rel="stylesheet"> I am using the same CSS files for other templates as base.html which is working fine and linking to them but for this particular HTML it is not linking, so I am trying to find the reason for this issue Here is the base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> ----------------------------------------------------- <link href='{% static "css/bootstrap.min.css" %}' rel="stylesheet"> <!-- Material Design Bootstrap --> <link href='{% static "css/mdb.min.css" %}' rel="stylesheet"> <!-- Your custom styles (optional) --> <link href='{% static "css/style.min.css" %}' rel="stylesheet"> -
How to connect Azure Redis Service in Django using django-redis Packages?
I wanted to config Redis with Django in Azure using azure redis one and as I learned through django-redis. we configure like this. CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": "mysecret" } } } What about configuring credentials for azure redis one? -
Can’t open file manage.py
enter image description here I’m trying to deploy my first django project on heroku, and the final step doesn’t work - can’t open manage.py. But there is manage.py in the directory I copied my project on the desktop, and with the original project manage.py worked fine. So in what may be a problem - the copy or heroku? -
Django REST Generic Class based Views
Can a generic like class based views be created that only needs a serializer object with CRUD functions of any models type be passed to it that can perform all the method handlers needed for an API to work? -
I get UnboundLocalError in Django website [duplicate]
I have been trying to debug this after some few days with no solutions yet, I would be glad if I could get a solution or suggestion. Thanks I get the UnboundLocalError, things were working perfectly but when I made some changes to my models.py to fix some other bug which got resolved, this came about. ERROR LOGS Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\student_management_app\HodViews.py", line 15, in admin_home all_student_count = student.objects.all().count() Exception Type: UnboundLocalError at /admin_home/ Exception Value: local variable 'student' referenced before assignment View.py def admin_home(request): all_student_count = student.objects.all().count() subject_count = Subjects.objects.all().count() course_count = Courses.objects.all().count() staff_count = Staffs.objects.all().count() # Total Subjects and students in Each Course course_all = Courses.objects.all() course_name_list = [] subject_count_list = [] student_count_list_in_course = [] for course in course_all: subjects = Subjects.objects.filter(course_id=course.id).count() students = student.objects.filter(course_id=course.id).count() course_name_list.append(course.course_name) subject_count_list.append(subjects) student_count_list_in_course.append(students) subject_all = Subjects.objects.all() subject_list = [] student_count_list_in_subject = [] for subject in subject_all: course = Courses.objects.get(id=subject.course_id.id) student_count = student.objects.filter(course_id=course.id).count() subject_list.append(subject.subject_name) student_count_list_in_subject.append(student_count) # For Staffs staff_attendance_present_list=[] staff_attendance_leave_list=[] staff_name_list=[] staffs = Staffs.objects.all() for staff in staffs: subject_ids = Subjects.objects.filter(staff_id=staff.admin.id) … -
Is it possible to user multiple custom user model in django?
I'm trying to make custom user model with AbstarcBaseUer in django 3.1. There are two types of user in my app. Reader, Publisher. Each model should have different fields, so I decided to make two tables for each. First I made Parent class for them, named User which inherit from AbstractBaseUser. class User(AbstarctBaseUser, PermissionMixin): email = models.EmailField(primary_key=True) USERNAME_FIELD = 'email' # and some other fields and setting Second I made Reader and Publisher class which inherit from User class. class Reader(User): # for Reader model Fields class Publisher(User): # for Publisher model Fields Is this structure available in django? And if it is, how do I override UserManger for these? -
Modify the DateField format shown on ModelAdmin list_display
On my ModelAdmin I'm able to see task_date DateField using the format I desire (which is # format='%Y-%m-%d'). However, when using list_display('task_date'), the same DateField is shown in another format. How can I specify the format that list_display needs to use for DateFields? On models.py class StaffTimeSheet(models.Model): time_sheet_owner = models.ForeignKey("Staff", on_delete=models.CASCADE) task_date = models.DateField(verbose_name='Date') # format='%Y-%m-%d' task_belongs_to_order = models.ManyToManyField("Order", related_name = 'order_present_in_timesheet_of') task_start_time = models.TimeField() task_end_time = models.TimeField() service_category = models.ManyToManyField("ServiceCategory", related_name = 'service_category_present_in_timesheet_of') task_description = models.TextField() def __str__(self): return str(self.time_sheet_owner) + " / " + str(self.task_date) + " / " + str(self.task_start_time) On admin.py class StaffTimeSheetModelAdmin(admin.ModelAdmin): #determines size of input text box formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'50'})}, models.TextField: {'widget': Textarea(attrs={'rows':2, 'cols':50})}, } fields = ['time_sheet_owner','task_date','task_belongs_to_order','task_start_time','task_end_time','service_category','task_description'] def task_belongs_to_project_order (self,staff_time_sheet_obj): return "\n".join([str(order.order_project.project_number) + "-" + str(order.order_number) for order in staff_time_sheet_obj.task_belongs_to_order.all()]) # TODO enforce a date format year-month-day list_display = ('time_sheet_owner','task_date','task_belongs_to_project_order','task_start_time','task_end_time','task_description') search_fields = ['task_date','task_description','task_belongs_to_order__order_number','task_belongs_to_order__order_project__project_number'] # TODO add task_belongs_to_project_order list_filter = ('time_sheet_owner','task_date',) admin.site.register(StaffTimeSheet, StaffTimeSheetModelAdmin) This is how the DateField looks when creating a new StaffTimeSheet object This is the list of created StaffTimeSheet objects in which I want to modify the format of the task_date DateField -
Created by field in a user's sub class
I need to have a "created_by" field in the sub user model which will show the User, who created Translator's account (is_translator=True). User model: class User(AbstractUser): is_client = models.BooleanField('Client status', default=False) is_translator = models.BooleanField('Translator status', default=False) Sub user: class Translator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) -
How do you use the Base64 Upload Adapter with Django-CKEditor?
Is there a way to use the Base64 upload adapter with django-ckeditor? If there isn't a simple way to do it, could I use a custom ckeditor build with the app? The django-ckedtor makes no mention of upload adapters at all, so I'm a little lost. -
Django static file not loaded/found
I have a small Django project and the css static files are not loaded when there are not in the app/static/app/css folder. I want to use project/project/static/css. However, it is not working even so I follow all tutorials and other posts, but it seems that I am missing something and this something took already some hours of my time and it is killing me. In the settings.py I have: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static") ] and my html template looks like this: <!DOCTYPE html> {% load static %} <html> <head> <title>Website</title> <link href="{% static 'css/warenkorb.css' %}" rel="stylesheet"> </head> <body> <h1>Hello user!</h1> <p>something you want</p> <img src="{% static 'images/img.jpg' %}"> </body> </html> I see it that way: os.path.join(BASE_DIR, "static") = ~/project/project/static and then I load this path in the html template and extend the rest to it like /css or /images, but nothing happens. My assumption is that for example "{% static 'css/warenkorb.css' %}" leads to ~/project/project/static/css/warenkorb.css Any advice is highly appreciated. Finding a solution is super annoying at this point, because I have no clue what is going on and no idea what else I could do. -
UnboundLocalError in Django web application
I have been trying to debug this after some few days with no solutions yet, I would be glad if I could get a solution or suggestion. Thanks I get the UnboundLocalError, things were working perfectly but when I made some changes to my models.py to fix some other bug which got resolved, this came about. ERROR LOGS Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\student_management_app\StaffViews.py", line 31, in staff_home students_count = student.objects.filter(course_id__in=final_course).count() Exception Type: UnboundLocalError at /staff_home/ Exception Value: local variable 'student' referenced before assignment View.py def staff_home(request): # Fetching All Students under Staff subjects = Subjects.objects.filter(staff_id=request.user.id) course_id_list = [] for subject in subjects: course = Courses.objects.get(id=subject.course_id.id) course_id_list.append(course.id) final_course = [] # Removing Duplicate Course Id for course_id in course_id_list: if course_id not in final_course: final_course.append(course_id) students_count = student.objects.filter(course_id__in=final_course).count() subject_count = subjects.count() # Fetch All Attendance Count attendance_count = Attendance.objects.filter(subject_id__in=subjects).count() # Fetch All Approve Leave staff = Staffs.objects.get(admin=request.user.id) leave_count = LeaveReportStaff.objects.filter(staff_id=staff.id, leave_status=1).count() #Fetch Attendance Data by Subjects subject_list = [] attendance_list = [] for subject in subjects: attendance_count1 = Attendance.objects.filter(subject_id=subject.id).count() … -
Django rest framework filter not working with django-2.1
1 I'm using Django 2.1, Django REST Framework(3.9) and Django Filters to filter the queryset. Program model has a foreign key to Department and thus want to filter based on DepartmentID When I try to search filter in rest framework it does not return filtered data. What am I doing wrong? class ProgramFilter(filters.FilterSet): class Meta: model = Program fields = ('programCode', 'pro_name', 'pro_shortForm', 'DepartmentID') class ProgramViewSet(viewsets.ModelViewSet): queryset = Program.objects.all() serializer_class = ProgramSerializer filterset_class = ProgramFilter filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) __basic_fields = ( 'programCode', 'pro_name','pro_shortForm', 'DepartmentID') filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ('programCode', 'DepartmentID') search_fields = ('DepartmentID') -
i want to show a html page in my Root Domain in Django
I Want to Show a HTML page in Root Domain in Django, tried to many times but, can't solve this problem, anyone help please. -
Codecoverage of a running server
For python you've got the codecoverage library to check your codecoverage. This works fine for unittests. However I'm interested to get the code coverage when running integration tests. I'm running the integration tests with cypress.io. So cypress.io is accessing a development server and runs the tests that way. I've tried to instrument the django development server the following way coverage run -p --source=code_folder ./manage.py runserver After the tests have run I run coverage combine and coverage report. Code that should have ran is marked as missing. So it seems like it's not properly instrumented. How can this be amended? -
Sending data between web-based app and desktop app
What is a generic concept of how to send data between a web-based app with Django and a desktop app with PyQT? For eg., user A fills in a form and uploads a data file to the web-based app. Another user B running the desktop app is to do some computation on the data file without the need to go into the web app (he has internet access, of course), and send result back to display on the web app of user A. You may ask, why not both users using the web app. This is due to responsibility separation and hardware access (user B has, but not user A). If someone could point to where or what to read up on this, thanks very much. -
Retrieve SocialAccount token and refresh token from django-allauth
I am trying to interface with the Gmail API using Django and django-allauth for authentication. I have configured my project according to the django-allauth documentation for Google. I am able to log in with a Google account and can see the account details on the Django admin page. Still I am unable to retrieve the token and refresh token to create a google.oath2.credentials.Credential object to pass to the Gmail API. Here is my current attempt: from allauth.socialaccount.models import SocialApp, SocialAccount from google.oauth2.credentials import Credentials def get_credentials(request): app = SocialApp.objects.get(provider='google') account = SocialAccount.objects.get(user=request.user) user_tokens = account.socialtoken_set.first() creds = Credentials( token=user_tokens.token, refresh_token=user_tokens.refresh_token, client_id=app.client_id, client_secret=app.client_secret ) return creds However, the user_token object is coming back as None, so the account.socialaccount_set must be empty. I'm not sure how this is possible if the request.user is correctly populated (I have verified that it is correct). Am I missing something? Any help is appreciated! -
Django - How to get checked objects in template checkboxes?
Im new in Django, I'm using xhtml2pdf for rendering data objects from template to PDF file , and i want to allow users to render only checked objects by checkboxes into pdf, is there anyway to filter that in Django ? Thanks views.py : def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode('ISO-8859-1')), result, link_callback=link_callback) if pdf.err: return HttpResponse('Error') return HttpResponse(result.getvalue(), content_type='application/pdf') class ViewPDF(View): @method_decorator(login_required(login_url='livraison:login_page')) def get(self, request, *args, **kwargs): checked_objects = [i dont know how to get them] queryset = Livraison.objects.filter(id__in=[checked_objects]) # i want something does that data = { 'livraisons' : queryset, 'now' : f'Livraisons-{date.today()}' } pdf = render_to_pdf('pdf_template.html', data) return HttpResponse(pdf, content_type='application/pdf')