Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where should PWA manifest be located for a Django app?
I'm working on converting a Django app to a Progressive Web App. Where should the manifest file be located in my directory structure if I link to the manifest? I am thinking of: <!-- Startup configuration --> <link rel="manifest" href="{% static 'app_name/manifest.webmanifest' %}"> I was working through the lighthouse plug-in feedback checklist to prep my website for use as a PWA and I ran into the message No usable web app manifest found on page. For Django converting to PWA, is there a preferred convention for this setup? -
Don't submit time past 11:59 pm
I have a form that creates a lesson with a date and time. I currently have validators to ensure that past dates can't be used, which are working perfectly. However, I am having trouble visualising how a validator that makes sure the time entered isn't past 11:59 pm would work. I inlucded a snippet of what I am trying to achieve (I know it doesn't work the way it is layed out, it is just there to provide context). I would appreaciate any help with this. forms.py def validate_date1(value): if value < timezone.now(): raise ValidationError('Date cannot be in the past') def validate_date2(value): if value < timezone.now(): raise ValidationError('Date cannot be in the past') def present_date1(value): if value > '11:59 pm': #raise ValidationError('Time cannot be past 11:59 pm') def present_date2(value): if value > '11:59 pm': raise ValidationError('Time cannot be past 11:59 pm') class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_datetime_start = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date1, present_date1]) lesson_datetime_end = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False, widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date2, present_date2]) lesson_weekly = forms.BooleanField(required=False) -
problem saving records contains foreign key to sqlite3 using Django and Ajax/json
I have two tables like: 1. Supplier(id, name, address) 2. Stoks(id, stok, supplier) in python shell: supplier = Supplier.objects.get(pk=1) stok=supplier.stoks.create(stok='books', supplier) in models.py: class Stok(models.Model): stok = models.CharField(max_length=30) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='stoks') in views.py: def new_stok(request, pk): supplier = get_object_or_404(Supplier, pk=pk) data = dict() if request.method == 'POST': form = NewStokForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True stoks = supplier.stoks.all() data['html_stok_list'] = render_to_string('stoks.html',{'supplier':supplier,'stoks':stoks}) else: data['form_is_valid'] = False else: form = NewStokForm() context = {'form': form, 'supplier':supplier} data['html_form'] = render_to_string('includes/partial_stok_create.html', context, request=request) return JsonResponse(data) in javascript file: $("#modal-book").on("submit", ".js-stok-create-form", function () { var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#stok-table tbody").html(data.html_stok_list); // <-- Replace the table body $("#modal-book").modal("hide"); } else { $("#modal-book .modal-content").html(data.html_form); } } }); return false; }); The record is not saved into database. where did I missed out? thanks -
Django NameError: name 'model' is not defined
I am altering an existing application so I can expand the use case a bit. I have already created a new model and altered the view and template a bit. Now I want to run migrations, but I keep getting the NameError and a Google search didn't provide me with much more information, especially since I am adding things to a working application rather than creating something from scratch. Is anyone able to help me? I have added the following line to admin.py: admin.site.register(InputData) the error: C:\var\www\SYSTEM>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File … -
Django - Show only a specific dynamic fields per models in django-eav2
I'm trying to figure it out on how I can show only a specific set of dynamic fields in eav to a unique registered model in my apps.models. But I don't know how to this, I've also read the documents but I can't seem to find anything about it, or maybe I've come across it and didn't understand. Now, what is happening is that, when I add an attribute in the django admin. It also adds the dynamic field in all the models registered in the eav. What I want to do is that; model 1 - dynamic_field1, dynamic_field2, dynamic_field3 model 2 - dynamic_field4, dynamic_field5, dynamic_field6 Btw, I'm currently using the django-eav2 the documentation is in the link. I've found my solution for my initial use case here link Below codes are basically on how to register my models to the eav. Here is my sample models class ClientName(models.Model): name = models.CharField(max_length=250, null=True, blank=True) description = models.TextField(null=True, blank=True) is_active = models.BooleanField(default=True) def __str__(self): return str(self.name) class CallDetails(models.Model): client_name = models.ForeignKey(ClientName, on_delete=models.PROTECT, null=True, blank=True, db_index=True) letter_info = models.TextField(null=True, blank=True) def __str__(self): return str(self.client_name) class Meta: verbose_name = 'Call Detail' ordering = ['client_name'] eav.register(ClientName) eav.register(CallDetails) below is my admin.py class CallDetailsAdminForm(BaseDynamicEntityForm): model … -
Why does my reply appear as a normal comment instead of being a reply to the a particular comment?
I am trying to make a reply function that will allow users to reply the comments but it is not able to display the reply as a child element . After getting posted it displays them as a normal comment. Here,s the models.py for comments class CommentManager(models.Manager): def all(self): qs = super(CommentManager,self).filter(parent = None) return qs class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments") name = models.CharField(max_length = 200) body = models.TextField(default = True) pub_date = models.DateTimeField(auto_now_add = True) parent = models.ForeignKey('self',null = True,blank = True) class Meta: ordering = ['-pub_date'] def __str__(self): return self.name def replies(self): return Comment.objects.filter(parent = self) @property def is_parent(self): if self.parent is not None: return False return True Here, s the views.py of comments def BlogDetail(request,pk): post = get_object_or_404(Post,pk = pk) comment = CommentForm(request.POST or None) subscribe = Subscribe() parent_obj = None if request.method == 'POST': subscribe = Subscribe(request.POST) comment = CommentForm(request.POST) if comment.is_valid(): comment.instance.post = post comment.save() try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id = parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() elif subscribe.is_valid(): subscribe = subscribe.save(commit = True) return render(request,'app/blog.html',{'blog_object':post,'comment':comment, 'subscribe':subscribe,'parent':parent_obj }) Here,s the html for comments and replies {% for i in blog_object.get_comments %} <div class="container"> <div class="row"> … -
Parsing a string containing logic to create Django Q objects
I'm adding reporting functionality to a django web application which includes being able to chain filters while defining the logic eg (1 OR 2 OR 4) AND 4 Currently the data structure being utilised is: `{'logic': u'(1 OR 2 OR 4) AND 4', 'query': [{u'field': u'first_name', u'id': 1, u'opertor': u'icontains', u'value': u'A'}, {u'field': u'first_name', u'id': 2, u'opertor': u'icontains', u'value': u'b'}, {u'field': u'show_tag', u'id': 3, u'opertor': u'includes', u'value': u'1955'}, {u'field': u'organisation__organisation_name', u'id': 4, u'opertor': u'icontains', u'value': u'a'}]}` To convert the logic from a string to a nested list I'm using the following: from pyparsing import nestedExpr def parse_brackets(val): val = '(' + val + ')' parsed = nestedExpr('(',')').parseString(val).asList() return parsed For the example above this returns [[['1', 'OR', '2', 'OR', '4'], 'AND', '4']] What I'm finding challenging is parsing this data structure so that it can be translated into chained Q() objects. I have tried using BFS to search through the structure but am unable to associate the AND/OR correctly to the surrounding criteria Any advice greatly appreciated! -
django-filter no matches
I couldn't find it in documentation so Im asking here. I've created filter with django-filter and it works properly, but if someone will select filters that none object has, then user will get empty page. I would like to add simple paragraph None criteria matches if filtered object don't exist. I've tried with template tags like {% if obj in filter.qs != none %} {% endif %} But it doesn't work. Does someone know how to make it? filters.py import django_filters from .models import Company, COMPANY_TECHNOLOGIES from django_filters import ChoiceFilter class CompanyFilter(django_filters.FilterSet): class Meta: model = Company fields = ['type', 'city', 'students'] def __init__(self, *args, **kwargs): super(CompanyFilter, self).__init__(*args, **kwargs) self.filters['type'].extra.update( {'empty_label': 'All'}) self.filters['city'].extra.update( {'empty_label': 'All'}) self.filters['students'].extra.update( {'empty_label': 'All'}) comp_list.html {% extends 'company/base.html' %} {% block content %} <div id="filter"> <form action="" method="get" id="submit"> {{ filter.form.as_p }} <input type="submit"/> </form> {% for obj in filter.qs %} <a href="/brands/{{obj.id}}">{{ obj.name }}</a> <p>Image {% if obj.image != None %} <img src="{{ obj.image.url }}"> {% endif%}</p> <p>Icon {% if obj.icon != None %} <img src="{{ obj.icon.url }}" width="30" height="30"> {% endif%}</p> <br> Type: {{ obj.type }} City: {{ obj.city }} Stack: {{ obj.stack }} <br /> <br> {% endfor %} {% endblock %}</div> -
Django is not recognizing my custom user's user type to enter a protected page view (RelatedObjectDoesNotExist: User has no usertype)
I am having issues with Django defining a custom user, which in this case is "cust" (short for customer) in Django 2.1. I have several other user types which contain separate registration forms to register them as a specific user type. I have built this from the tutorial "How to Implement Multiple User Types with Django" by Vitor Freitas, which eliminates Django's default user management system. My goal is to have a protected view (customer hub) which only customers can enter, and so on for other user types. Below is the error and code which comprises my project: Traceback RelatedObjectDoesNotExist at /companyusers/cust/ User has no cust. File "/home/companysite/.virtualenvs/env/lib/python3.7/site-packages/django/views/generic/edit.py" in get 189. self.object = self.get_object() File "/home/companysite/companysite/companyusers/views/cust.py" in get_object 38. return self.request.user.cust File "/home/companysite/.virtualenvs/env/lib/python3.7/site-packages/django/utils/functional.py" in inner 214. return func(self._wrapped, *args) File "/home/companysite/.virtualenvs/env/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py" in __get__ 414. self.related.get_accessor_name() Exception Type: RelatedObjectDoesNotExist at /companyusers/cust/ Exception Value: User has no cust. models.py This file is where I classify each of the custom user types (i.e, I have 2 other classes and Booleans which are written identically). class User(AbstractUser): is_cust = models.BooleanField(default=False) class Cust(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='cust', primary_key=True) cust.views.py This is the views file for the customer, which includes the form and hub view. … -
django testing: post request with a Form with paramters
I want to test that my view redirects after I send it correct data. The problem is that I'm using a form that needs parameters while initializing. I have a method that builds me a response that I later use in the tests. The method works for my other views but I can't make it work with views that use Forms that need parameters to initialize them. In my forms.py I've got: class SupportIssueForm(forms.ModelForm): class Meta: model = SupportIssue fields = ('user', 'property', 'title', 'text', 'is_urgent', 'is_service') def __init__(self, person_company, properties, is_property, *args, **kwargs): super(SupportIssueForm, self).__init__(*args, **kwargs) self.fields['is_service'].widget.attrs['class'] = 'custom-control-input' ... My method for generating respone I'm later using in my test looks like this: def generate_logged_in_user_post_response(self, data): request = self.factory.post(self.url, data={**self.form_class_args[0], **data}) request.user = self.logged_in_user return new_support_issue_view(request) I also tried this: def generate_logged_in_user_post_response(self, data): form = SupportIssueForm(**self.form_class_args[0], data=data) request = self.factory.post(self.url, form) request.user = self.logged_in_user return new_support_issue_view(request) the self.form_class_args[0] is some dictionary I declare elsewhere: { "person_company": person_company, # <querry object> "properties": properties, # <querry object> 'is_property': False } -
Adding foreignkey to model_to_dict - Django 1.11
I have this method, which saves a parent model fields into 2 child models: def save(self, *args, **kwargs): if not self.pk and self.__class__.__name__ == 'Parent': Child1.objects.create(**model_to_dict(self)) Child2.objects.create(**model_to_dict(self)) super().save(*args, **kwargs) But, on Parent model I have a field like: team_lead = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_('decision team lead'), on_delete=models.PROTECT, null=True, blank=True ) Whenever I try to save the parent it throws me this: Traceback (most recent call last): File "C:\ifavirtualenv\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\ifavirtualenv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\ifavirtualenv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\KKOCI\ifa_kkoci\new_ifa\IfA\ifa_standards_rms\apps\tlevels\views.py", line 26, in get_wireframe form.save() File "C:\ifavirtualenv\lib\site-packages\django\forms\models.py", line 468, in save self.instance.save() File "C:\Users\KKOCI\ifa_kkoci\new_ifa\IfA\ifa_standards_rms\apps\tlevels\models.py", line 176, in save TLevelsDraft.objects.create(**model_to_dict(self)) File "C:\ifavirtualenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\ifavirtualenv\lib\site-packages\django\db\models\query.py", line 392, in create obj = self.model(**kwargs) File "C:\ifavirtualenv\lib\site-packages\django\db\models\base.py", line 555, in __init__ _setattr(self, field.name, rel_obj) File "C:\ifavirtualenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 216, in __set__ self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "1": "TLevelsDraft.team_lead" must be a "User" instance. ERROR:django.request:Internal Server Error: /tlevels/wireframe Traceback (most recent call last): File "C:\ifavirtualenv\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\ifavirtualenv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\ifavirtualenv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
Sourcecode protection of Django application
i know there are already several post about this topic floating around the web but i would like to maybe get some state-of-the-art context here. I want to protect the source code of my django app. primary target is that an attack is not able to properly manipulate source code so i only see two option here. either .py files will get compiled or protected by some kind of third party DRM solution which are indeed in all cases that i know crap... excuse my language but somebody owns the key for that files and i generally trust nobody. Anyway is there a practical solution to accomplish this? Maybe obfuscate and later compile the source to .pyc ? greetz :) -
How to make a game run from entering a url
this is my first question posted here, and I'm relatively new to coding so forgive me if its a bit silly. Anyways, i'm trying to make a simple website that all it does is taking a url request and 'returns' a game as a 'httpresponse'. I made the game using Python 3.7, I'm using django to make my game act as a 'web app', and I'm using pythonanywhare to make it accessible on the internet. My question is can i do that, and if so, how? Thanks! -
'provide the namespace argument to include() instead.' % len(arg)
I am new to Djanogo and following tutorial point to learn Django - python. While trying to map the URL to displaying the message in views page I am getting below error. My Code is: view.py from django.shortcuts, import render from django.http import HttpResponse # Create your views here. def hello(request): text = "<h1>Hello!, Welcome to Eschol Prayer House!!!</h1>" return HttpResponse(text) url.py """escholchurch URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ url('admin/', include(admin.site.urls)), url('hello`enter code here`/', 'mylchurch.views.hello', name = 'hello'), ] Error: File "C:\Python\Python37\lib\site-packages\django\urls\conf.py", line 27, in include 'provide the namespace argument to include() instead.' % len(arg) django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and … -
How to run external script inside django project?
I am unable to run python script inside my django project. I have creates a directory with mkdir scripts Then I use touch scripts/__init__.py Then I create my python script using touch scripts/update_keyword.py here is the code of my script def run(): # Fetch all questions print("run script") Then I run my script with the help of the following command: python manage.py runscript update_keyword.py Now I am getting following error: Unknown command: 'runscript' Type 'manage.py help' for usage. I have follow this blog https://django-extensions.readthedocs.io/en/latest/runscript.html . Kindly Help. -
Getting Deadlock while updating in bulk in django
Getting Deadlock while updating transactions in bulk using django function "bulk_update" in with transaction.atomic()? can someone help me here? -
django-apscheduler schedule a job to run at a specific time of the day
There isn't much available in the https://github.com/jarekwg/django-apscheduler . I want to set a job which will run exactly at 12:00 AM each day. How to set that up in django-apscheduler? What I have tried so far is this: @register_job(scheduler, "interval", days=1) def pending_block_activity_notification(): print("Job started") How to specify it to run once a day at exactly 12:00 am? My configuration will run at an interval of 1 day but the interval is counted from when the django server is being started. -
Django won't load a css file even though others from the same folder are being loaded?
This is what I am seeing when I do view page source. <!-- Custom styles for this template --> <link rel='stylesheet' href="/static/css/cover.css" /> <!--<link rel="stylesheet" href="/static/css/cover.css" />--> <link rel='stylesheet' href="/static/css/main.css" /> The error: The current path, cover.css, didn't match any of these. When I go to the href of cover.css I get a path not found error. The main.css is in the same folder and works perfectly. I am on Django 2.1.7 I was getting the same problem with another css file which when I went to incognito mode the file loaded. I am not sure what I am doing wrong here. Thanks -
Django: foreignkey values with get() method
I need to know how can I get foreignkey field´s values instead of ID with the get method. I´m sending a queryset from view to template as a JsonResponse. An specific instance info, so I use the get() method def TareaDetailView(request): ID = request.POST.get('id') tareas_todas = Tareas.objects.values() tarea = tareas_todas.filter(pk=ID).get() return JsonResponse({'tarea': tarea}) I get the info at the browser but with the field names change from "empresa" to "empresa_id", for example. This is my model with the original field names. class Tareas(models.Model): creador = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) destinatario = models.ForeignKey(User, related_name='destinatario', blank=True, null=True, on_delete=models.CASCADE) titulo = models.CharField(max_length=100, blank=True, null=True) tarea = models.TextField(max_length=500, blank=True, null=True) resuelto = models.BooleanField(default=True) fecha_creacion = models.DateField(default=datetime.date.today, blank=True, null=True) fecha_limite = models.DateField(default=datetime.date.today, blank=True, null=True) fecha_resuelto = models.DateField(default=datetime.date.today, blank=True, null=True) empresa = models.ForeignKey("Contactos", blank=True, null=True, on_delete=models.CASCADE) persona_empresa = models.ForeignKey("Personas", blank=True, null=True, on_delete=models.CASCADE) And this is what I can check at the browser console. tarea: creador_id: 1 destinatario_id: 1 empresa_id: 6 fecha_creacion: "2019-03-10" fecha_limite: "2019-03-15" fecha_resuelto: "2019-03-10" id: 210 persona_empresa_id: 3691 resuelto: false tarea: "Habrá que hacer alguna cosa maravillosa." titulo: "Esta es una tarea de prueba" An this is teh Ajax I use to get the data and show it in the template. <script> $(function(){ $('.show_tarea').on('click', … -
Django logger disabled when using Gunicorn
I am trying to use Django logging with gunicorn. I am able to use it with Django development server, but when I use with gunicorn logs are not being written to file or console. Here is my logging config(stripped down): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(filename)s:%(lineno)s] %(message)s' }, 'simple': { 'format': '%(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'docs_file_handler': { 'class': 'logging.FileHandler', 'filename': os.path.join(LOGS_DIR, 'docs.log'), 'level': 'DEBUG', 'formatter': 'simple' } }, 'loggers': { 'docs.views': { 'handlers': ['docs_file_handler', 'console'], 'propagate': True, 'level': 'DEBUG', }, }, } When I print the 'logger.disabled' it comes out True. To get the logger: logger = logging.getLogger(__name__) print(logger.handlers) # Returns [<FileHandler /var/efs/docs.log (DEBUG)>] print(logger.disabled) # Returns True Gunicorn command: gunicorn my_project.wsgi --enable-stdio-inheritance --log-level "info" --error-logfile "/var/efs/gunicorn.error.log" --access-logfile "/var/efs/gunicorn.access.log" --reload I am unable to get the logs to work with Gunicorn. -
Django Rest Framework, improperly configured lookup field
I'm getting the error Could not resolve URL for hyperlinked relationship using view name "taxonomy-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Here is a MWE: urls.py: from django.contrib import admin from django.urls import include, path from rest_framework import routers from testproj import views router = routers.DefaultRouter() router.register(r'taxonomy', views.TaxonomyViewSet) router.register(r'taxonomy-term', views.TaxonomyTermViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) ] models.py: from django.db import models class Taxonomy(models.Model): name = models.CharField(max_length=255) description = models.TextField() slug = models.SlugField() def __str__(self): return self.name class Meta: verbose_name = "Taxonomy" verbose_name_plural = "Taxonomies" class TaxonomyTerm(models.Model): taxonomy = models.ForeignKey( "Taxonomy", on_delete=models.CASCADE, related_name="terms", related_query_name="term" ) parent = models.ForeignKey( "self", on_delete=models.CASCADE, related_name="children", related_query_name="child", blank=True, null=True ) name = models.CharField(max_length=255,) description = models.TextField() slug = models.SlugField(unique=True) def __str__(self): return self.name class Meta: verbose_name = "Term" verbose_name_plural = "Terms" serializers.py: from testproj.models import TaxonomyTerm, Taxonomy from rest_framework import serializers class TaxonomySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Taxonomy fields = ('name', 'description', 'slug') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } class TaxonomyTermSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TaxonomyTerm fields = ('taxonomy', 'parent', 'name', 'description', 'slug') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } views.py from … -
How to wait for payment after form is submitted and then do code once verified
I have a page where users currently insert some information related to the task they're submitting to my webpage. I have setup Stripe for payments due my service being resource intensive, but i'm in a place where I need some advice for how to tackle my issue. This is the flow I would like: A user inputs their information to the task and clicks submit on the form -> They're redirected to Stripe's payment site where they input their credit card info > My code waits for confirmation that the payment has succesfully been sent > Then computes my underlying code after My current issue is that, Stripe requires an Payment ID that must be set in the Javascript code <script> stripe.redirectToCheckout({ sessionId: "{{context}}", }).then(function (result) { // Diplay result.error.message to your customer }); </script> But as far as I know I can't change this value after the template has been rendered? This Payment ID is first generated after the form has been submitted. Also when Stripe get's the payment ID it redirects the page to their website where the user insert the credit card info, but can this happen while my site does it code in the background and … -
Omitting password field for custom django user model
I want to have my own custom Django user model with only the email id,first_name, last_name and date_joined fields.I don't want to have a password column since the authentication happens via Microsoft SAML and hence I don't need to store any passwords.My user model is as follows: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import PermissionsMixin, BaseUserManager, AbstractBaseUser from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): def _create_user(self, email, **extra_fields): if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, extra_fields) user.save() return user def create_superuser(self, email, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): full_name = f'{self.first_name} {self.last_name}' return full_name.strip() However, when i run the migrations, I can see the password field also in the user table.What am i doing wrong ? -
An web development program to control the flow of water
solution for the given vedio clipping https://youtu.be/2muASl0wVJA -
Django rest framework JWT , delete the jwt token
How to expire django rest framework JWT token manually ? Because it does not store the token in the database. Is there any correct way to expire the token ? I am thinking to continue with middleware where token will be stored per user. At every login request we will update the token in the db for a user. At every request, we will fetch the token from request and comapre with the stored token and if doesnt match then we'll return the forbidden. I dont know its a correct way or not !!