Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to override the content of notification email from a test case update in Kiwi TCMS?
Im trying to change the content of the notification email sent after a test case has been updated to better clarify what has been changed. As it is, the content is hard to read. Went through the link below to configure the other notification content: http://kiwitcms.org/blog/atodorov/2018/08/06/how-to-override-templates-for-kiwi-tcms/ The content of the notification email: Updated on Tue Aug 20 15:47:18 2019 Updated by Admin --- notes +++ notes @@ -1 +1 @@ -TestTest +TestTest123123 --- text +++ text @@ -10,7 +10,7 @@ 3. item *Expected results*: - +Test 1. item 2. item 3. item I managed to replicate the example (from the link) for post_case_delete, post_run_save, and user_registered but the dir(tcms/templates/email/) lacks one for test case updates. Is there a way to amend how the content is shown in the notification email? -
Dojo: all xhr / ajax calls seem to be synchronous and block other calls
I am working on a CRM we inherited. Long story short - there is a button that calls a php script which should run in background and we don't need to wait for response. request(idata+'transferInTimeExec.php',{ sync: false, preventCache:true, method:'GET' }); Now, the transferInTimeExec.php takes an hour to run, it's a very complex script that deals with weekly timesheets for a recruitment company, processes them, does a lot of DB operations etc. Using Chrome. Every time I press the button to run it, it blocks all the xhr calls until it finishes. CRM is "ajax heavy" and while the script is running, the user can't do anything, not even navigate away from that page. Even when I open a new browser tab and try to do something, it won't do it. If I open the CRM in another browser (Firefox) while the script is running, I can use the CRM. In Network tab - the first one is pending, and as you can see all the subsequential calls to a different Ajax call wait (all have sync:false) I even replaced the whole logic with PHP function sleep(30) to make it just do nothing for 30 seconds before returning anything - same … -
In django, how can I ensure that a specific user is accessing a view?
I would like to be able to check if the user accessing a page is a specific user. For instance, when a user accesses the "Edit Post" page on my blog app, I want to ensure that the user is the author of the post. Currently, I check that the user accessing '/Blog/Edit//' has the blog.change_post permission. However, if a second user (who also has that permission) were to enter the URL to change someone else's post, they would pass that permission check and be able to edit someone else's post. What I want is a @user_passes_test function that check's the user object accessing the view against the author attribute of the post. #/Blog/urls.py urlpatterns = [ ... path('Edit/<int:pk>', views.BlogEdit, name='BlogEdit'), ... ] #/Blog/views.py @permission_required('blog.change_post', login_url='/Portal/login') def BlogEdit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('/Blog', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'Blog/Edit.html', {'form': form}) -
MultipleObjectsReturned- get() returned more than one UserDetails -- it returned 10
For my project i am doing a resume parser. When i upload one resume, it was able to extract those data. When i upload more resume i get this error, i understand it does matter with get() or filter(). I have tried changed my user details user_detail = UserDetails.objects.get(user=user) from get() to filter(), although it resolve the multiple object error, but it having another issue is my result extract nothing, no result show at all. It means it doesn't extract any data from my resume although upload successful def homepage(request): if request.method == 'POST': user = User.objects.get(id=1) UserDetails.objects.filter(user=user).delete() Competencies.objects.filter(user=user).delete() MeasurableResults.objects.filter(user=user).delete() Resume.objects.filter(user=user).delete() ResumeDetails.objects.filter(resume__user=user).delete() file_form = UploadResumeModelForm(request.POST, request.FILES) files = request.FILES.getlist('resume') if file_form.is_valid(): for file in files: try: user = User.objects.get(id=1) # saving the file resume = Resume(user=user, resume=file) resume.save() # extracting resume entities parser = resume_parser.ResumeParser(os.path.join(settings.MEDIA_ROOT, resume.resume.name)) data = parser.get_extracted_data() # User Details # resume.name = data.get('name') # resume.email = data.get('email') # resume.education = get_education(data.get('education')) user_details = UserDetails() user_details.user = user user_details.name = data.get('name') user_details.email = data.get('email') user_details.mobile_number = data.get('mobile_number') user_details.skills = ', '.join(data.get('skills')) user_details.years_of_exp = data.get('total_experience') user_details.save() for comp in data.get('competencies'): competencies = Competencies() competencies.user = user competencies.competency = comp competencies.save() for mr in data.get('measurable_results'): measurable_results = MeasurableResults() measurable_results.user = … -
Understanding Django CSRF_COOKIE_SAMESITE and CSRF_TRUSTED_ORIGINS
Obviously I have a problem to understand the impact of Django (2.2.4) settings regarding CSRF parameters in a cross-domain environment. As I have already noticed I have to set SESSION_COOKIE_SAMESITE = None if I want to place my Django application into an iframe of a website with another domain (e.g. Django app on foo.com and iframe on bar.com) in order to send forms on my Django application. However what's about the CSRF parameters? After some trials I noticed that I can only send the Django form in the iframe if I also set CSRF_COOKIE_SAMESITE = Nonein the Django settings. But what is the CSRF_TRUSTED_ORIGINS for? If I set the iframe domain (e.g. bar.com) into the list ['bar.com'] instead of CSRF_COOKIE_SAMESITE = None I can not send the form on my Django app in the iframe. Could anybody explain in what case CSRF_TRUSTED_ORIGINS has any effect? Is it just usable in an environment with one domain and serveral subdomains? Thanks for any hint! -
Sort the elements of list contains salutation in it?
I have a list contains salutation in it. How can I sort the list on the basis of names in pythonic way? I have tried to split the elements of list on the basis of '.' character and sorted the names but could not get salutation with names. names = ["Mr.usman", Mrs.obama, "Mr.Albert"] sorted_list = sorted([i.split('.')[1] for i in names]) For e.g ["Mr.usman", Mrs.obama, "Mr.Albert"] should be like ["Mr.Albert", Mrs.obama, "Mr.usman"] -
Unable to import TokenObtainPairView,TokenRefreshView from JWT
I want to use Json Web token authentication. but when I import, it gives me error of no reference of TokenObtainPairView, TokenRefreshView, found, however I installed jwt. urls.py: from django.contrib import admin from django.urls import path from rest_framework_jwt.views import ( TokenObtainPairView, TokenRefreshView, ) from django.conf.urls import url,include urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), url(r'^auth/', include('authsystem.urls')) Settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } when I do pip freeze I have the packages: Django==2.2.4 django-cors-headers==3.1.0 djangorestframework==3.10.2 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==4.3.0 Pillow==6.1.0 PyJWT==1.7.1 pytz==2019.2 sqlparse==0.3.0 I have tried to import from different way but still it giving me cannot find reference. -
bin/python3: cannot execute binary file: Exec format error
I just made a new django project, pushed it to git and now I am trying to go deploy it using Digital ocean. I installed all the needful things like pip, python etc. but I am not able to make the python manage.py runserver work. ((g-v) is my virtualenv so that is not the problem.) It is throwing this error: (g-v) root@ubuntu-s-4vcpu-8gb-blr1-01:/home/g-v/src# python manage.py runserver File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax I read a few posts that recommended trying out python3 manage.py runserver but when I try that, I get this error: (g-v) root@ubuntu-s-4vcpu-8gb-blr1-01:/home/g-v/src# python3 manage.py runserver -bash: /home/g-v/bin/python3: cannot execute binary file: Exec format error My pip list command outputs: (g-v) root@ubuntu-s-4vcpu-8gb-blr1-01:/home/g-v/src# pip list DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Package Version ----------------------------- ---------- astroid 1.6.6 autopep8 1.4.4 backports.functools-lru-cache 1.5 certifi 2019.6.16 configparser 3.7.4 Django 1.11.23 enum34 1.1.6 futures 3.2.0 isort 4.3.21 lazy-object-proxy 1.4.1 mccabe 0.6.1 pip 19.2.2 pipenv … -
Object of type "" is not JSON serializable
I am trying to create an API and pass the context data in Response but I am getting the error: Object of type TakenQuiz is not JSON serializable Below is the code: taken_quizzes = quiz.taken_quizzes.select_related('supplier__user').order_by('-date') total_taken_quizzes = taken_quizzes.count() quiz_score = quiz.taken_quizzes.aggregate(average_score=Avg('score')) least_bid = quiz.taken_quizzes.aggregate(least_bid=Min('least_bid')) extra_context = {'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes, 'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids, 'driver_num': driver_num, 'lat_lon_orig': lat_lon_orig, 'lat_lon_dest': lat_lon_dest, 'user_pass': user_pass, 'username': username, 'password': password, } print("extra content is ", extra_context) return Response(extra_context) Here is the context data: extra content is {'taken_quizzes': <QuerySet [<TakenQuiz: TakenQuiz object (1)>]>, 'total_taken_quizzes': 1, 'quiz_score': {'average_score': 0.0}, 'least_bid': {'least_bid': 899}, 'matching_bids': [], 'driver_ num': 0, 'lat_lon_orig': '36.1629343, -95.9913076', 'lat_lon_dest': '36.1629343, -95.9913076', 'user_pass': ('jkcekc', 'efce'), 'username': 'efw', 'password': 'sdf'} The error I believe is because of the queryset in the extra_context, How do I resolve this ? I tried json.dumps but it still doesn't work -
How to show the email address of sender correctly in django?
How to show the logged in user email address whenever I send email to bilalkhangood6@gmail.com? Although every time it shows me another email address(bilalkhangood4@gmail.com) who is not logged in. I used user.request.email to send email from those user who is logged in. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False views.py from django.contrib.auth.models import User def ViewSendEmail(request): send_mail('Hello from Bilal Khan', 'Hello there, This is an automated message.', user.request.email, #FROM ['bilalkhangood6@gmail.com'], #TO fail_silently=False) return render(request, 'nextone/email_send.html') -
how to customize django password forms, do not use default password form
I am customize reset password form for my django project, however, it always direct to the default password form?? I can customize the login and signup form no problem, but comes to password reset it just direct to the default password form. I do not know what happen? I use django 2.2 project/urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), ] project/users/urls.py from django.urls import path from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), ] project/users/views.py f rom django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') password_reset_url = reverse_lazy('password_reset') template_name = 'signup.html' project/users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email', 'age',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'age',) my directory -
How can i get min value in array from JSONField
i have a model and this model have a JSONField class Book(models.Model): data = JSONField() And this field have an array. data = { 'outlet':[ {'price': 100}, {'price': 200}, {'price': 300} ]} I want to get min value of outlet price.I've tried use KeyTextTransform and Min func. I can do easily if outlet not an array. But unfortunately i have to work on array in this case. -
Convert django view to django rest framework APIView
I am trying to convert a django view to APIView, here's the normal view and below is what I tried. Django View @method_decorator([login_required, teacher_required], name='dispatch') class QuizResultsView(DetailView): model = Quiz context_object_name = 'quiz' template_name = 'classroom/teachers/quiz_results.html' def get_context_data (self, **kwargs): quiz = self.get_object() if (quiz.status == 'Assigned'): """Some Code""" cursor = connection.cursor() def dictfetchall (cursor): desc = cursor.description return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] """ Some More Code """ extra_context = {'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes, 'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids, 'driver_num': driver_num, 'lat_lon_orig': lat_lon_orig, 'lat_lon_dest': lat_lon_dest, 'user_pass': user_pass, 'username': username, 'password': password, } kwargs.update(extra_context) return super().get_context_data(**kwargs) else: cursor = connection.cursor() def dictfetchall (cursor): desc = cursor.description return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] cursor.execute('''SELECT STATEMENT''', [quiz.id]) """ Some More Code """ extra_context = {'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes, 'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids} kwargs.update(extra_context) return super().get_context_data(**kwargs) def get_queryset (self): return self.request.user.quizzes.all() According to the documentation I added : REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] } in my settings.py and instead of return super().get_context_data(**kwargs) i used return Response(extra_content) but it doesn't seem to work. What is it that I am doing wrong? Please, help!! -
Django model setup on existing Oracle table
I have a particular situation which I need help clarifying. I have an existing Oracle table with an auto increment ID as a primary key I am creating a django model to sync with that table so i can make use of django's ORM methods such as save(), filter() etc. I read from the django docs the .save() method can perform both a UPDATE and INSERT depending on if the values passed to the primary key results in a True value (i.e. not a None or null). In my table I have two columns which together will form a composite primary key. If I specify primary_key = True on the two attributes on the django model, do I need to remove the primary key tag from oracle table? Also, do i need to specify the unique_together to tell the django model that they are unique or will it be able to derive the index i created in the django oracle table? Thanks. -
Is there any method to connect Vue JS and Django together without using Django REST API
I am a newbie to programming world. I know how to integrate Vue JS and Django by creating the Django REST API and Vue JS(with Axios). Is there any other way I can use the Django and Vue JS together ? Because I felt it hard to make a secure Django Rest API but normal Django templating system comes with in build user authentication and creating web app is super easy. I have used normal Django templating system and added Vue JS through CDN links, it works fine for each page. My real intention was to create a website that do not reload when user clicks each page. Do you recommend AJAX for this purpose ? -
Auto fill the text field after one text field is filled django
Now I am having two text field and I would like to do the following function: Name: Name ID: If I enter the name, then the name id will be auto filled with the corresponding id in my database. Which I already have all the name and name id in my model. my model: Name: xxx abc hehe haha Name ID: 123 456 789 525 Name: xxx Name ID: 123 <--- Auto insert after the xxx is filled -
Why column containing some of the django fields in html table collapsing when rendered to pdf using xhtml2pdf?
I am trying to generate pdf in Django using xhtml2pf. The HTML template consists mostly of HTML table. Django PhoneField and EmailField are getting collapsed while pdf is rendered. Below is the image of pdf generated when passing Django PhoneField and EmailField in context- The context for html template is as follows- user_dict = { "full_name": user.full_name, "email": str(user.email), "phone_number": str(user.phone_number), "emergency_number": "very very long header", "id_proof_number": user.id_proof_number } When I am using the plain string in place of django field it is rendered correctly as below- Context used is as follows- user_dict = { "full_name": user.full_name, "email": "joe@gmail.com", "phone_number": "+14151234567", "emergency_number": "very very long header", "id_proof_number": user.id_proof_number } Django Model- class User(models.Model): trip = models.ForeignKey( Trip, on_delete=models.CASCADE, related_name="users") id_proof_number = models.CharField( _("Id Proof"), max_length=100, null=True, blank=True) full_name = models.CharField(_("Full name"), max_length=255) email = models.EmailField(_("email"), max_length=70) phone_number = PhoneNumberField(_("Phone Number")) emergency_number = PhoneNumberField(_("Emergency Number"), default=None, null=True) HTML Template- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User Details</title> <style type="text/css"> @page { size: A4; margin: 1cm; } .card-header{ text-align: center; } .table{ border: 0.5px solid #ababab; text-align: center; width: 100%; max-width: 100%; margin-bottom: 5px; table-layout:fixed; } .table tr th td{ white-space: nowrap; } .table th { padding: 5px; vertical-align: top; background-color: … -
alter option automatically in search bar according to another option
I want that when we change the value of the state the value of the city also changes according to the values in this state search.html <div class="form-row"> <div class="col-md-6 mb-3"> <label class="sr-only">State</label> <select name="city" class="form-control"> <option selected="true" disabled="disabled">State</option> {% for key,value in state_choices.items %} <option name="state" value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-md-6 mb-3"> <label class="sr-only">City</label> <select name="city" class="form-control"> <option selected="true" disabled="disabled">Cité</option> {% if state.value == "Nabeul" %} {% for key,value in Nabeul_Choices.items %} <option name="city" value="{{ key }}">{{ value }}</option> {% endfor %} {% endif %} </select> </div> </div> choices.py state_choices = { 'Tunis':'Tunis', 'Nabeul':'Nabeul', } tunis_choices = { 'Tunis':'Tunis', 'Le Bardo':'Le Bardo', 'Le Kram':'Le Kram', } Nabeul_Choices = { 'Nabeul':'Nabeul', 'Hammamet':'Hammamet', 'Dar Chaabane':'Dar Chaabane', } view.py def search(request): queryset_list = Listing.objects.order_by('-list_date').filter(is_published=True, type='Vendre') if 'state' in request.GET: state = request.GET['state'] if state: queryset_list = queryset_list.filter(state__iexact=state) if 'city' in request.GET: city = request.GET['city'] if city: queryset_list = queryset_list.filter(city__iexact=city) context = { 'Nabeul_Choices' : Nabeul_Choices, 'tunis_choices' : tunis_choices, 'state_choices' : state_choices, } return render (request, 'listings/search.html', context) the code works but when I change state the cities do not change automatically -
How to send email to official account from logged in user in django?
I am trying to send email from the user who is logged in to an account which I have given bilalkhangood4@gmail.com. But I have typed it manually. There could be more accounts means more users from which I want to send. But how could I send email from just those users who are logged in? Basically it is an APP where a user will click on withdraw button to request and send mail to official admin account. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False views.py from django.contrib.auth.models import User def ViewSendEmail(request): send_mail('Hello from Bilal Khan', 'Hello there, This is an automated message.', 'bilalkhangood6@gmail.com', #FROM ['bilalkhangood4@gmail.com'], #TO fail_silently=False) return render(request, 'nextone/email_send.html') -
How to make Self hosted Blogging platform like medium?
i want to make blogging platform like medium, with my own custom features this features include. . 1.user can have self hosted blog inside my website 2.i want to make easy to understand tools for cms, like image gallery,code snippet,video player(it must very robust and seamless,not complex at all) 3.to reader i want to make highlight feature,and comment section,bookmark,reading reminder 4.i want to track reader behavior, like how much they spent in reading, track how much people read your blog 5.have a follow system 6.publisher can get revenue from my own ads service,(like youtube ads system,they make ads work seamlessly with their content) 7.make advance search with machine learning . should i use php for my own cms ? -
What is the difference between using brackets "[]" and parentheses "()" for "fields" in django-rest-framework
I have seen fields in the django-rest-framework initialized/declared with parentheses () and brackets [] and I am wondering if there is a difference. I have only been using () but I see [] in the documentation everywhere. Say we have a model Dog. class Dog(models.Model): favorite_food = models.CharField(max_length=255) Now would it be correct to say that these two serializers below for this Dog model are the same? Even though the field is declared with different ASCII characters. class DogSerializer(serializers.ModelSerializer): class Meta: model = Dog fields = ('id', 'favorite_food') class DogSerializer(serializers.ModelSerializer): class Meta: model = Dog fields = ['id', 'favorite_food'] -
How do you create a deferred field if your field is a SerializerMethodField?
I want to create a deferred method field in a model serializer using drf-flexfields. I am using Django Rest Framework and drf-flexfields. I want to create a method field in my model serializer to make a complex query. Because retrieving this field will incur extra database lookups, I want this to be a deferred field, i.e. it will only be retrieved if the client specifically asks for it. The DRF-Flexfields documentation seems to infer that a field can be deferred by only listing it in "expanded_fields" and not in the normal "fields" list, but gives no further explanation or example. https://github.com/rsinger86/drf-flex-fields#deferred-fields I have tried creating a simple SerializerMethodField to test this: class Phase(models.Model): name = models.CharField(max_length=100) assigned = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="phases_assigned") class PhaseSerializer(FlexFieldsModelSerializer): assignable_users = serializers.SerializerMethodField("get_assignable_users") expandable_fields = { 'assignable_users': (UserSerializer, {'source': 'assignable_users', 'many': True}), } class Meta: model = Phase fields = ['name', 'assigned'] def get_assignable_users(self, phase): return User.objects.all() I get the following error : "The field 'assignable_users' was declared on serializer PhaseSerializer, but has not been included in the 'fields' option." What is the correct way to go about accomplishing this? -
ValueError: invalid literal for int() with base 10: 'glassdoor' while creating a user object from custom user model
I have a custom user model called User. I tried to populate some data. I successfully created a superuser. However, when I try to create a normal user, this Error appears:" ValueError: invalid literal for int() with base 10: 'glassdoor'" where glassdoor is the password. Anyone know how to fix this? In my custom user model, I only made email as my login requirements and omit username, also added some other attributes. I did not override default django password settings. models.py class User(AbstractUser): #use email as authentication username = None email = models.EmailField(_('email address'), unique=True) objects = CustomUserManager() # id = models.AutoField(primary_key=True) USER_TYPE_CHOICES = ( (1, 'doctor'), (2, 'labPeople'), (3, 'receptionist'), (4, 'patient'), (5, 'admin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,null=True) sex = models.BooleanField(blank=True, null=True) tel_no = models.CharField(max_length=255, blank=True, null=True) dob = models.DateField(db_column='DOB', blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_type',] def __str__(self): return self.email managers.py for managing my custom user model from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.db import models import django class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ use_in_migrations = True def _create_user(self, email, user_type, password, **extra_fields): """ … -
How to change hidden-input value then send it using django forms?
Good evening, I have a problem with ajax in django forms, it refuses to change value of a hidden input send the views.py class. The page configuration.html contains a form that selects number of parameters. In addition, i need to create a new variable using the previous ones called list_items that changes its value according to the selected parameters, to send it i used a hidden input tag <input id="combo" name="combinaison" class="btn btn-success col-lg-12" type="hidden" value="test"> The variables are send to views.py but the problem is that the value of the hidden input doesn't changed, it always shows the default value. I tried using document.getElementsByName("combinaison").value = list_items; in the form but the value never changes. Here is configuration.html {% extends "base.html" %} {% load staticfiles %} {% block body_block %} <!-- Bootstrap core JavaScript--> <script src="{% static 'staticfiles/vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'staticfiles/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Core plugin JavaScript--> <script src="staticfiles/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="staticfiles/js/sb-admin-2.min.js"></script> <script src="staticfiles/vendor/app/app_config.js"></script> <!-- Begin Page Content --> <div class="container-fluid"> <!-- Grow In Utility --> <div class="col-lg-7"> <div class="card position-relative"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Parametres</h6> </div> <div class="card-body"> <form action="/try" method="GET"> <script> var i = 0; var list_items = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; </script> … -
How do I dynamically set timezones in Django?
So I have been creating a simple site where I need to display the timezones of the time a post was created. So far I have set it to Victoria, Australian time, because it is my timezone, but I want people from other countries to have their own timezones on the posts. I know it sounds silly, but I tried to add multiple timezones to the TIME_ZONE variable in settings.py, but I learnt that does nothing but cast errors. LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Australia/Victoria' So when I put multiple timezones in, I expected it to dynamically show the time based on where you are, but it didn't, I just got a syntax error.