Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django call related model queryset like rails activerecord merge scope
Say we have two models Employer and Department: class Profile < ApplicationRecord belongs_to :account scope :age_upper, ->(age) { where("age > ?", age) } end class Account < ApplicationRecord has_one :profile end Then we can have a query on Department model in Rails like this: >>> Account.joins(:profile).merge(Profile.age_upper(18)) But with Django: class ProfileQuerySet(models.QuertSet): def age_upper(age): return self.filter(age__gt=age) class Profile(models.Model): account = models.ForiegnKey('Account', on_delete=models.CASCADE) objects = models.Manager.from_queryset(ProfileQuerySet)() class Account(models.Model): pass My question is can we query from Account using filter age_upper of Profile instead of rewrite another one for Account like below class AccountQuerySet(models.QuertSet): def age_upper(age): return self.filter(profile__age__gt=age) class Account(models.Model): objects = models.Manager.from_queryset(AccountQuerySet)() -
django-rest-framework multiple lookup_fields
The code below try's to lookup the Car Object based on the url of: example.com/<user>/<slug>/. The error i'm receiving is: invalid literal for int() with base 10: 'exampleUsername' from the url of : example.com/exampleUsername/exampleCarSlug/. The code below is able to lookup the Car Object if i use the userID instead of the user's username, e.g example.com/<user_id>/<slug>/ = example.com/20/exampleCarSlug/ that is if i replace all instances of user with user_id in the code below. What i would like to know, is how can i lookup the Car Object using the user's username (string) instead of the user's ID (integer). Url urlpatterns = [ url(r'^car/(?P<user>\w+)/(?P<slug>[\w-]+)/$', CarAPIView.as_view(), name='car'), ] View from django.shortcuts import get_object_or_404 class MultipleFieldLookupMixin(object): """ Apply this mixin to any view or viewset to get multiple field filtering based on a `lookup_fields` attribute, instead of the default single field filtering. """ def get_object(self): queryset = self.get_queryset() # Get the base queryset queryset = self.filter_queryset(queryset) # Apply any filter backends filter = {} for field in self.lookup_fields: if self.kwargs[field]: # Ignore empty fields. filter[field] = self.kwargs[field] obj = get_object_or_404(queryset, **filter) # Lookup the object self.check_object_permissions(self.request, obj) return obj class CarAPIView(MultipleFieldLookupMixin, RetrieveAPIView): queryset = Car.objects.all() serializer_class = CarSerializer permission_classes = [IsAuthenticatedOrReadOnly] lookup_fields = … -
Python3, re.match with list
I read this : https://stackoverflow.com/a/17090205/6426449 And I made a list that cannot be used on username in django. list : FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner'] So I made a code like this : views.py def username_choice(request): if request.method == "POST": username = request.POST['username'] for item in forbidden.FORBIDDEN_USERNAME_LIST: match = re.search("r'\b"+item+"\b'", username) if match: return JsonResponse({'result': item + 'banned username'}) But It seems that it does not work. Maybe I think, match = re.search("r'\b"+item+"\b'", username) Here is problem. How can I fix that? -
how to save PDF file generate by WeasyPrint django in a folder directory
I'm trying save a .pdf file in a folder using WeasyPrint with django==1.11 with python3.4, but I don't found nothing about this issue. file_location = '%s/uploads/cartas/%s.pdf' % (settings.MEDIA_ROOT, car_key) html_string = render_to_string('tpl-export-pdf.html', context) html = HTML(string=html_string, base_url=request.build_absolute_uri()) #html.write_pdf(target=file_location, stylesheets=[CSS(settings.STATIC_ROOT + '/app/css/table.css')]) result = html.write_pdf(target=file_location, stylesheets=[CSS(settings.STATIC_ROOT + '/app/css/table.css')]) response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'attachment; filename=%s.pdf' % car_key response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) I'm getting this error on Debug Mode Request Method: GET Request URL: http://127.0.0.200/admin/cartafrete/export/pdf/240531/ Django Version: 1.11 Exception Type: TypeError Exception Value: 'NoneType' does not support the buffer interface Exception Location: /usr/lib/python3.4/tempfile.py in func_wrapper, line 538 Python Executable: /usr/bin/python3 Python Version: 3.4.3 -
I never granted the permission I'm checking for, yet the view works as if I granted the permission
I implemented a permission check but it doesn't hold. Here is the CBV using a PermissionRequiredMixin: class PreferenceUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): form_class = PreferenceUpdateForm model = Profile template_name = 'user_profile/preference_edit.html' permission_required = ('user_profile.change_profile', 'user_profile.can_change_profile', 'user_profile.can_change') I'm visiting the view by changing the pk in the URL. My current user should not be allowed to see this preference update page, as it does not belong to the request.user. However even after listing the permission_required, I am allowed to view the page. Shouldn't the page only show if I user.user_permissions.add(permission)? -
Django oracle its not working
I already install oracle client 12.2 also i installed pip instal cx_Oracle but this error seeing. I given my database connection settings to settings.py im sure its completely true but whats the error exactly mean ? Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run web_1 | self.check_migrations() web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 422, in check_migrations web_1 | executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 20, in __init__ web_1 | self.loader = MigrationLoader(self.connection) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 52, in __init__ web_1 | self.build_graph() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 209, in build_graph web_1 | self.applied_migrations = recorder.applied_migrations() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations web_1 | self.ensure_schema() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema web_1 | if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor web_1 | return self._cursor() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor web_1 | self.ensure_connection() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__ web_1 | six.reraise(dj_exc_type, dj_exc_value, traceback) web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise web_1 | raise value.with_traceback(tb) web_1 | … -
Get a tuple value in a tuple by index
for a Django Model i needed an extra field to set a special month. This was done with the choices attribute an a tuple set: class Timeline(models.Model): MONTHS = ( (1, _("January")), (2, _("February")), (3, _("March")), (4, _("April")), (5, _("May")), (6, _("June")), (7, _("July")), (8, _("August")), (9, _("September")), (10, _("October")), (11, _("November")), (12, _("December")), ) tldate_mth = models.IntegerField(_("Month"), choices=MONTHS, default=1) In admin section this works fantastic. Now i want to output the month in my template: # ... def to_string(self): return "%s (%s / %d)" % (self.title, self.MONTHS.index(self.tldate_mth), self.tldate_yr) But then i got the message "tuple.index(x): x not in tuple". What did i wrong? -
python-docx document-styles font failed to the Heading style
I have used python-docx in my django project to MS-word report, and I modified the Normal content style successfully, I have got the '宋体' font: document.styles['Normal'].font.name = u'宋体' report.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') document.styles['Normal'].font.size = Pt(9) But when I use it to the Heading content, the Heading font did not change. no any failed shows.Curiously, the Heading size was changed. Why this happened, how to solve this? document.add_paragraph('1.清单', 'Heading 1') document.add_paragraph('设备:', 'Heading 2') document.styles['Heading 1'].font.name = u'宋体' document.styles['Heading 1']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') document.styles['Heading 1'].font.size = Pt(12) document.styles['Heading 2'].font.name = u'宋体' document.styles['Heading 2']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') document.styles['Heading 2'].font.size = Pt(10.5) And I want to konw how to modify Chinese and English fonts respectively? Thanks! -
Manage image uploaded in a form: copy paste to another model when POST and dropdown display in Django
The project I'm working on is an application made to facilitate the creation of PDF technical sheets via a big form. In order to be able to erase or edit the values without any impact the already created PDF sheets, I duplicated my models so that 1 is linked to a main model with fk or m2m and the other is independent. I make the form from the main model. Until I submit the form, the data comes from my independent models (so I don't use Form nor modelForm). When I POST, I want it to be copied and pasted on the equivalent model (the one linked to the main model). I have dropdown lists to choose the information. If the data I need doesn't exist yet, I have a modal "create new ..." that allows me to create a new one that is dynamically added to the dropdown list. Everything works well, except for the ImageField. The new images and their information are well stocked into the independent model but not transferred into the equivalent one and the line in the dropdown list displays "undefined" values. I've read about non compatibility between JSON and imagefields, that's why I indicated … -
How can I serialize the OneToOneField to be list in Django-Rest-Framework?
How can I serialize the OneToOneField to be list? I have two Model: class SwitchesPort(models.Model): """ SwitchesPort """ name = models.CharField(max_length=32) profile = models.CharField(max_length=256) class Server(models.Model): ... switchesport = models.OneToOneField(to=SwitchesPort, related_name="server", on_delete=models.DO_NOTHING, null=True) You see, they are OneToOne relationship. In the SwitchesPortSerializer, I only can set the physical_server many=False: class SwitchesPortSerializer(ModelSerializer): """ SwitchesPort """ physical_server = ServerSerializer(many=False, read_only=True) class Meta: ... If I set True there will reports error, because they are one to one relationship. The result will be like this: [ { "name": "switches_port01", "profile":"", "physical_server": { "name": "server01", ... } }, ... ] But, I want to get the physical_server as a JSON list, not the JSON object, how can I do that in Django-Rest-Framework? My requirement data is like this: [ { "name": "switches_port01", "profile":"", "physical_server": [ { "name": "server01", ... } ] }, ... ] Although the relationship is one-to-one, I still want to get the list, not the object. Is it feasible to get that? -
python.manage.py runserver got many Importing xxx_ImagePlugin
After I update django version to 2.0 and begin to work with virtual environment when run the command: python manage.py runserver my log got many lines with info related Importing xxx_ImagePlugin. All work OK but I do not understand why its appear each time and how to remove its from the log? log: 2017-12-27 09:05:49, Importing BmpImagePlugin 2017-12-27 09:05:49, Importing BufrStubImagePlugin 2017-12-27 09:05:49, Importing CurImagePlugin 2017-12-27 09:05:49, Importing DcxImagePlugin 2017-12-27 09:05:49, Importing DdsImagePlugin 2017-12-27 09:05:49, Importing EpsImagePlugin 2017-12-27 09:05:49, Importing FitsStubImagePlugin 2017-12-27 09:05:49, Importing FliImagePlugin 2017-12-27 09:05:49, Importing FpxImagePlugin 2017-12-27 09:05:49, Importing FtexImagePlugin 2017-12-27 09:05:49, Importing GbrImagePlugin 2017-12-27 09:05:49, Importing GifImagePlugin 2017-12-27 09:05:49, Importing GribStubImagePlugin 2017-12-27 09:05:49, Importing Hdf5StubImagePlugin 2017-12-27 09:05:49, Importing IcnsImagePlugin 2017-12-27 09:05:49, Importing IcoImagePlugin 2017-12-27 09:05:49, Importing ImImagePlugin 2017-12-27 09:05:49, Importing ImtImagePlugin 2017-12-27 09:05:49, Importing IptcImagePlugin 2017-12-27 09:05:49, Importing JpegImagePlugin 2017-12-27 09:05:49, Importing Jpeg2KImagePlugin 2017-12-27 09:05:49, Importing McIdasImagePlugin 2017-12-27 09:05:49, Importing MicImagePlugin 2017-12-27 09:05:49, Importing MpegImagePlugin 2017-12-27 09:05:49, Importing MpoImagePlugin 2017-12-27 09:05:49, Importing MspImagePlugin 2017-12-27 09:05:49, Importing PalmImagePlugin 2017-12-27 09:05:49, Importing PcdImagePlugin 2017-12-27 09:05:49, Importing PcxImagePlugin 2017-12-27 09:05:49, Importing PdfImagePlugin 2017-12-27 09:05:49, Importing PixarImagePlugin 2017-12-27 09:05:49, Importing PngImagePlugin 2017-12-27 09:05:49, Importing PpmImagePlugin 2017-12-27 09:05:49, Importing PsdImagePlugin 2017-12-27 09:05:49, Importing SgiImagePlugin 2017-12-27 09:05:49, Importing SpiderImagePlugin 2017-12-27 09:05:49, Importing … -
Print Dates range if they are available in Database
from below code i am going to print date ranges that's fine but what the problem is i need to print the date ranges , those available in database only [this image shows the created_at date field which is in look model . I need these dated to be printed if user select the date rage between dec 1 to dec 30 ]1 while (current_date >= from_date): r = r + 1 ws.write(0,r,current_date,style) current_date -= timedelta(days = 1) -
500 Internal Server Error: Python 3.5, Django and mod_wsgi
I'm trying to deploy a Python/Django application on DigitalOcean and getting the following error: apache error.log [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Target WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Exception occurred processing WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py'. [wsgi:error] [pid 17060] Traceback (most recent call last): [wsgi:error] [pid 17060] File "/var/www/demo-app/src/demo/demo/wsgi.py", line 12, in <module> [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Target WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Exception occurred processing WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py'. [wsgi:error] [pid 17060] Traceback (most recent call last): [wsgi:error] [pid 17060] File "/var/www/demo-app/src/demo/demo/wsgi.py", line 12, in <module> [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' My setup is as follows: Ubuntu==16.04 django==1.11.4 apache==2.4.18 mod-wsgi==4.5.22 python 3.5(virtualenv) libapache2-mod-wsgi-py3 Any ideas on what I'm missing? -
Providing a initial list for related_name field cannot be accessed
Models (Employee has a foreign key to Company with related_name employees): class Company(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=1023) class Employee(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='employees') name = models.CharField(max_length=255) staffId = models.IntegerField() active = models.BooleanField(default=False) View: class CompanyForm(CreateView): model = Company fields = '__all__' template_name = 'forms/company_form.html' def get_initial(self): initial = super(CompanyForm, self).get_initial() initial['employees'] = [Employee(name='Ann', staffId=10, active=True), Employee(name='John', staffId=2, active=False)] return initial Template: <head> </head> <body> <form id="myForm" method="post"> {% csrf_token %} {{ form.as_p }} {% for employee in form.employees %} <p>{{ employee.name }}</p> {% endfor %} <input type="submit" value="Save"> </form> </body> And this is what I see rendered: I expected to see the two names of the Employee objects I passed in get_initial method. Why doesn't this work and what can I do to get it working? -
EDITGetting error main() takes 2 positional arguments but 3 were given
I am testing out google adwords api features (NOTE: This question isnt direactly aimed at Google Ad Words API). I am facing an error that says : main() takes 2 positional arguments but 3 were given Heres what I have done: 1) Created a Keyword model that has a keyword charfield 2) Created a KeywordForm that has a form element of type CharField 3) Used the form in a html page to get the keyword through the POST method 4) After the POST, the url is routed to a view keyword_add which sets two values namely adwords_client = adwords.AdWordsClient.LoadFromStorage() ad_group_id = 'XXXXXXXXX ' .Also it gets the value of keyword model using new_keyword = Keyword.objects.all() . It then calls a function located in a python script using the function call ad_group_update.main(adwords_client, ad_group_id, new_keyword) 5) The function main in the python script add_keywords is executed using the three arguments adwords_client, ad_group_id & new_keyword The following error arises when i do this : 1) error while executing main() Apart from this error I have another question in the code: from googleads import adwords AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def main(client, ad_group_id, keyword): # Initialize appropriate service. ad_group_criterion_service = client.GetService( 'AdGroupCriterionService', version='v201710') # Construct keyword … -
Passing Parameters to upload_to Parameter in Django File Upload
I am using the following post to upload files in Django: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html. In the post, it mentions that the upload_to parameter can be a callable that returns a string. In the example provided, the callable accepts two parameters, instance and filename as follows: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) At what point and how do I pass parameters to upload_to? I am using form.save(commit=True) to persist form values to the database. Any help would be appreciated. Thanks. -
Django Rest Framework: Derived model serializer fields
I'm working on building a tree-like hierarchical database system using Django Rest Framework and django-polymorphic-tree. I have two models- BaseTreeNode and DescriptionNode (the later one is derived from BaseTreeNode). Specifically, here's my models.py: class BaseTreeNode(PolymorphicMPTTModel): parent = PolymorphicTreeForeignKey('self', blank=True, null=True, related_name='children', verbose_name=_('parent')) title = models.CharField(_("Title"), max_length=200) def __str__(self): return "{}>{}".format(self.parent, self.title) class Meta(PolymorphicMPTTModel.Meta): verbose_name = _("Tree node") verbose_name_plural = _("Tree nodes") # Derived model for the tree node: class DescriptionNode(BaseTreeNode): description = models.CharField(_("Description"), max_length=200) class Meta: verbose_name = _("Description node") verbose_name_plural = _("Description nodes") So, each title field (belonging to BaseTreeNode) has an associated description field (belonging to DescriptionNode) with it. Now, all I want to have is a JSON that returns a nested representation of my entire tree. For now, I have only defined a simple serializer with a recursive field. My serializers.py from rest_framework_recursive.fields import RecursiveField class DescriptionNodeSerializer(serializers.ModelSerializer): class Meta: model = DescriptionNode fields = ('description',) class BaseTreeNodeSerializer(serializers.ModelSerializer): subcategories = serializers.ListSerializer(source="children",child=RecursiveField()) class Meta: model = BaseTreeNode fields = ('id', 'title', 'subcategories') Which gives me (for BaseTreeNodeSerializer only): [ { "id": 1, "title": "Apple", "subcategories": [ { "id": 2, "title": "Contact Person", "subcategories": [] }, { "id": 3, "title": "Sales Stage", "subcategories": [ { "id": 4, "title": "Suspecting", "subcategories": … -
Get the dates for the created date only
models.py class UserWay(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateField() updated_at = models.DateTimeField(auto_now=True) class Grades(models.Model,): user_ql = models.OneToOneField(UserQuickLook, related_name = "grades_ql") health = models.CharField() overall = models.FloatField() views.py to_date = request.GET.get('to_date',None) from_date = request.GET.get('from_date', None) while to_date >= from_date: r = r + 1 ws.write(0,r,current_date,style) to_date -= timedelta(days = 1) user will fill the form daily that form is going to store. my problem is need to show the dates from date range of filled form . per one day only once it is going to filled -
Unable to fetch list value - django
my posted data looks like this : QueryDict: {u'question': [u'how to'], u'submit': [u'submit'], u'tag_name': [u'one', u'two'], u'csrfmiddlewaretoken': [u'WtOIVwdti7pBaT9LwyYtReS2WEoRpXVJXXLqCDgHaZi14OMmSXkE8g7ccTVTJ48h'], u'ansc': [u'multi'], u'options': [u'3']} I'm trying to fetch 'tag_name' data, but each time I do request.POST.get('tag_name') all i get is two I'm not able to fetch entire list, even after looping entire request object. How to fetch this object ? -
How to replace the key name in Serializer?
I have a ModelSerializer: class PublicNetwokSerializer(ModelSerializer): """ PublicNetwok """ class Meta: model = PublicNetwok fields = "__all__" The model is bellow: class PublicNetwok(models.Model): name = models.CharField(max_length=12) desc = models.CharField(max_length=24) ... You know if I use the ModelSerializer I will get all the key-values like bellow: [ { "name":"xxx", "desc":"xxx", }, { "name":"xxx", "desc":"xxx", } ] But I want to change the key desc to description, in Django-Rest-Framework how to access that? -
Django Rest Framework: Could not resolve URL for hyperlinked relationship using view name "post-detail"
I found a lot of answers to the similar issue, but none of them helped me. I am new to the backend and Django, I already spend a few days trying figure out what I am doing wrong, but no success. You guys my lest hope, cause I don't know what to try more... I would appreciate the help a lot! So, when I call http://127.0.0.1:8000/users/{user_name}/ I am getting : ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "post-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. If I change HyperlinkedRelatedField on any other field it's working properly... urls.py app_name = 'api' urlpatterns = [ url(r'^posts/(?P<post_id>\d+)/$', PostDetails.as_view(), name='post-detail'), url(r'^users/(?P<username>[\w\-]+)/$', UserPosts.as_view()), ] views.py class PostDetails(APIView): """ - GET a post """ def get(self, request, post_id): post = Post.objects.get(id=post_id) post_serializer = PostSerializer(post) return Response(post_serializer.data) class UserPosts(APIView): """ GET all user posts """ def get(self, request, username): user = User.objects.get(username=username) serializer = UserSerializer(user, context={'request': request}) return Response(serializer.data) serializer.py class UserSerializer(serializers.ModelSerializer): posts = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='post-detail', lookup_field='id') # Mandatory for UUID serialization user_id = serializers.UUIDField() class Meta: model = User exclude = ('id', 'password') read_only_fields = ('created', 'username', … -
Display different div element components when Toggle switch slider
// I want to have a toggle switch which if slide left a div content components pops up and on slide right a different div content pop up.How can I proceed? HTML CONTENT <form> <label class="switch"> <input type="checkbox" checked="true" > <div class="slider round"></div> </label> </form> <div id ="menu1"> Menu 1 conetnt </div> <div id ="menu2"> MEnu 2 content </div> CSS CONETENT /* The switch - the box around the slider */ .switch { position: relative; display: inline-block; width: 60px; height: 34px; } /* Hide default HTML checkbox */ .switch input {display:none;} /* The slider */ .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } /* STRUCTURE //As you can see I want like if the toggle slides right content of div id="menu1" to be displayed … -
Django JWT HTTP Authorization not passing
I am trying to use JWT token authentication with Django rest framework. I was able to successfully get the access and refresh token. And I made sure that the token is valid. But when I try to access some protected apiview with the access token. It says {"detail":"Authentication credentials were not provided."}. curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTE0MzQzNzcxLCJqdGkiOiIwYmE5YTcxZTJmMzQ0YmRmOTM1ZWQ3MTU3ZmI2NDkyZiIsInVzZXJfaWQiOjh9.dI3t8yvNe2Z7MKXojGvFpq_Etf1cLg8QSYsNobJ6jQ0" http://localhost:8000/users/me/ However, on server side I did get the request.META with a HTTP_AUTHORIZAITON field that contains the above token. I'm currently developing on localhost instead of Apache, with following files and configurations: In views.py: class GetMyInfo(views.APIView): def get(self,request): print(request.META) user = request.user profile = user.profile profile_serializer = ProfileSerializer(instance = profile) return Response(profile_serializer.data, status = HTTP_200_OK) In url.py: urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^api/$', get_schema_view()), re_path(r'^api/auth/', include('rest_framework.urls')), re_path(r'^api/auth/token/obtain/$', TokenObtainPairView.as_view(), name = 'token_obtain_pair'), re_path(r'^api/auth/token/refresh/$', TokenRefreshView.as_view(), name = 'token_refresh'), re_path(r'^api/auth/token/verify/$', TokenVerifyView.as_view(), name = 'token_verify'), #re_path(r'^api-token-auth/', authviews.obtain_auth_token, name = 'obtain_auth_token'), re_path(r'^users/$', views.CreateUser.as_view(), name = 'register'), re_path(r'users/(?P<uuid>[0-9a-f-]+)/$', views.GetUserInfo.as_view(), name = 'info'), re_path(r'users/me/$', views.GetMyInfo.as_view(), name = 'myinfo'), ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api' ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework_simplejwt.authentication.JWTAuthentication', #'rest_framework.authentication.SessionAuthentication', #'rest_framework.authentication.TokenAuthentication', #'rest_framework.authentication.BasicAuthentication', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } AUTH_USER_MODEL = 'api.User' In models.py: @receiver(post_save, sender = settings.AUTH_USER_MODEL) def create_auth_token(sender, instance = … -
Django-Paypal using the signals to create Order History
I'm using the django-paypal on my django website project, everything is working good, the payment is working and i'm getting to signals back to my website. After testing it a bit, I can see the signals registered at the admin page under Paypal IPN. I'm try to make a page that only the admin user can see, with all the orders that have been made, for example "{user] paid 20$ for {name} at {date.time}" any tips and help would be awesome !!! -
How can i implement EAV in django?
I am extremely new to Django and I am trying to implement EAV within my application. I cannot find any examples of how to do this so would anyone mind posting a quick random example of how it would be programmed? Thanks!