Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Problems setting up django-allauth URLs
I'm trying to customize a few things of allauth and ran into the following problem. I got my own account app, which is supposed to handle all the customization I do to allauth amongst other account related stuff. Which means I want to include the allauth urls into the urls.py located in my account app, not in the project level urls.py. However when I try it with the code below I run into the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'account_login' not found. 'account_login' is not a valid view function or pattern name. project/urls.py urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( ... path('account/', include('apps.account.urls')), # This does not work # path('account/', include('allauth.urls')), # This works ... ) apps/account/urls.py urlpatterns = [ ... path('', include('allauth.urls')), #This is where I want to include the allauth urls ... ) Going one step further: Can I customize the allauth urls in some way? When I try something like the following I get the same error as above: apps/account/urls.py from allauth.account import views as allauth_view urlpatterns = [ ... path("signup/", allauth_view.signup, name="account_signup"), ... ) -
TypeError: on_delete must be callable
Suddenly I am getting an error saying TypeError: on_delete must be callable. I don't know how to solve this error as I don't see field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category'), mentioned anywhere in my code. File "/home/arch/myproject/main/migrations/0014_auto_20191025_1154.py", line 6, in <module> class Migration(migrations.Migration): File "/home/arch/myproject/main/migrations/0014_auto_20191025_1154.py", line 47, in Migration field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category'), File "/home/arch/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 801, in __init__ raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable. -
Django says ImproperlyConfigured: The included URLconf does not appear to have any patterns in it
I'm new to Django and I'm facing a problem with a repo I downloaded. It sends the error File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\urls\resolvers.py", line 596, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'quiniela.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. My quiniela.urls looks like this: from django.contrib import admin from django.urls import path from quinewhats.views import Home from django.contrib.auth.views import LogoutView from django.urls import include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', Home.as_view()), path("logout/", LogoutView.as_view(), name="logout"), path('liga/',include('liga.urls',namespace='liga')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And my liga.urls like this: from django.urls import path from .views import EquiposTableView,EquiposCreateView,EquiposUpdateView,EquiposDeleteView, LigaTableView, LigaCreateView, LigaUpdateView, LigaDeleteView, TorneosTableView,TorneosCreateView,TorneosDeleteView,TorneosUpdateView app_name='liga' urlpatterns = [ path('equipos/table/', EquiposTableView.as_view(), name='tabla_equipos'), path('equipos/create/',EquiposCreateView.as_view(), name='crear_equipos'), path('equipos/update/<int:pk>/',EquiposUpdateView.as_view(), name='actualizar_equipos'), path('equipos/delete/<int:pk>/',EquiposDeleteView.as_view(), name='eliminar_equipos'), path('liga/table/', LigaTableView.as_view(), name='tabla_liga'), path('liga/create/', LigaCreateView.as_view(), name='crear_liga'), path('liga/update/<int:pk>/', LigaUpdateView.as_view(), name='actualizar_liga'), path('liga/delete/<int:pk>/', LigaDeleteView.as_view(), name='eliminar_liga'), ] I don't know what a circular import is, but I read it could be that my urls.py was somewhat imported to a views.py, but I checked and it doesn't seem to be the case. Is there any other thing I'm overseeing, or some other information that could be useful? … -
registering multiple models in Django Admin and excluding common field
I am registering my (numerous) models using looping through apps.get_models() much like in the below answer: Register every table/class from an app in the Django admin page My goal: as most of the models contain a common field that I would like to exclude from Django Admin I wonder if there is any way to do it without resorting to registering each model separately with exclude = FieldToBeExcluded -
('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: contains
I have models like: class Gtex1(models.Model): id = models.TextField(primary_key=True) sample = models.TextField(blank=True, null=True) gtex_s4q7_0003_sm_3nm8m = models.FloatField(db_column='GTEX-S4Q7-0003-SM-3NM8M', blank=True, null=True) gtex_qv31_1626_sm_2s1qc = models.FloatField(db_column='GTEX-QV31-1626-SM-2S1QC', blank=True, null=True) gtex_13ovi_1026_sm_5l3em = models.FloatField(db_column='GTEX-13OVI-1026-SM-5L3EM', blank=True, null=True) class Tcga1(models.Model): id = models.ForeignKey(Gtex1, models.DO_NOTHING, db_column='id', primary_key=True) sample = models.TextField(blank=True, null=True) tcga_we_aaa0_06 = models.FloatField(db_column='TCGA-WE-AAA0-06', blank=True, null=True) tcga_86_8668_01 = models.FloatField(db_column='TCGA-86-8668-01', blank=True, null=True) tcga_d8_a146_01 = models.FloatField(db_column='TCGA-D8-A146-01', blank=True, null=True) I have almost 30 models like Tcga1 having the same primary key (id) which is a foreign key from the Gtex1 model. I am trying to do this: search_models=[models.Gtex1,models.Tcga1,models.Tcga2,models.Tcga3] search_results = [] search_query='tcga_61_2111_01' for m in search_models: fields=[x for x in m._meta.get_fields()] search_queries=[Q(**{x.name + "__contains" : search_query}) for x in fields] q_object = Q() for query in search_queries: q_object = q_object | query results = m.objects.filter(q_object) search_results.append(results) print(search_results) which is basically going through all models column names and finding search query and filter through it. However, I am getting ERROR like: raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: contains If anyone can help me understand how to resolve this or any insights will be helpful and appreciated. Thank you so much. -
Not able to login to the django admin
Hello I am creating a web app locally (postgres), and is trying to login to the django admin. However whenever I login using the correct credentials the server stops running. The last log says [10/Dec/2019 16:37:11] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 The url .../admin/ shows me the expected login form and if I fill in the form incorrectly I get relevant error messages. If I fill in the form correctly with the details of a superuser (created via manage.py createsuperuser) then the page does not redirect and the server suddenly stops. settings.py INSTALLED_APPS = [ 'pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] urls.py urlpatterns = [ path('', include('pages.urls')), path('listings/', include('listings.urls')), path('admin/', admin.site.urls), ] I have done the fix from Djando admin wont log in, no errors but had no success. Any help is appreciated! -
Django ManyToMany object saving to different database
I have a Django app that uses multiple databases - one for each client. When saving new objects, I use the .save(using=db) to specify which database the object should be saved to. Models class Document(models.Model): name = models.CharField(max_length=500, unique=True) class Dataset(models.Model): name = models.CharField(max_length=500, unique=True) documents = models.ManyToManyField(Document, related_name="doc_datasets") Saving dataset = Dataset(name = "myDataset") dataset.save(using = db) # Success! The object is saved in the correct database. document = Document(name = "myDocument") document.save(using = db) # Success! The object is saved in the correct database. I am running into issues when trying to add a many-to-many relationship: dataset.documents.add(document) # This attempts to save to a default database (non-client specific) How do I specify the database when adding a related object? -
Python - Splitting a string of names separated by spaces and commas
I have an API feeding into my program into a django many to many model field. The names of the individuals within my database are structured with a separated first name and last name. However, the API is sending a bulk list of names structured as as a string list as so: "Jones, Bob Smith, Jason Donald, Mic" (Last name-comma-space-first name-space-new last name- etc.) How would I separate this string in a way that would allow me to filter and add a particular user to the many-to-many field? Thanks!! -
How to upgrade my django 2.2 project to 3.0 and support asgi?
Recently Django releases a 3.0 version with an inbuild asgi version. I have created a Django project using django 2.2 but I want to support inbuild asgi without using channels. What are the possible ways to migrate from django 2.2 to 3.0 so that the project can support inbuild asgi? -
Django error ['“foo” is not a valid UUID.']
I recently resetted my database and now Django raises the error ['“2” is not a valid UUID.'] when visiting any site. The UUID is set as pk in my model and database and I am logged in properly with a superuser account. I don't know where Django gets the 2 from and what causes the error? Model: from django.contrib.auth.models import AbstractUser from django.db import models import uuid class CustomUser(AbstractUser): DID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.username View: from django.urls import reverse_lazy from django.views.generic.edit import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' Error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/users/login/ Django Version: 3.0 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'Wiki_app', 'Dashboard', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2309, in to_python return uuid.UUID(**{input_form: value}) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\uuid.py", line 169, in __init__ raise ValueError('badly formed hexadecimal UUID string') During handling of the above exception (badly formed hexadecimal UUID string), another exception occurred: File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, … -
Django TemplateSyntaxError at / 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls
I get the error when i run the code. python3 manage.py runserver TemplateSyntaxError at / 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log propeller static tz Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0 Exception Type: TemplateSyntaxError Exception Value: 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log propeller static tz Exception Location: /home/sggs/neerajbyte/Env-10-DeC/lib/python3.7/site-packages/django/template/defaulttags.py in find_library, line 1025 Python Executable: /home/sggs/neerajbyte/Env-10-DeC/bin/python3 -
Django Settings.py - SECRET_KEY - KeyError
Currently have a Django project running on Python 3.6.9 , hosted on Digital ocean using Gunicorn and Nginx. I am attempting to switch my SECRET_KEY and other passwords to environment variables opposed to having them as a string in settings.py. When doing so I run into the following error and Gunicorn shuts down. Dec 10 15:22:20: File "/home/user/projectdir/project/project/settings.py", line 23, in <module> Dec 10 15:22:20 droplet_name gunicorn: SECRET_KEY_PULL = os.environ['SECRET_KEY'] Dec 10 15:22:20 droplet_name gunicorn: File "/home/user/projectdir/myenv/lib/python3.6/os.py", line 669, in __getitem__ Dec 10 15:22:20 droplet_name gunicorn: raise KeyError(key) from None Dec 10 15:22:20 droplet_name gunicorn: KeyError: 'SECRET_KEY' Dec 10 15:22:20 droplet_name gunicorn: [2019-12-10 15:22:20 +0000] [20022] [INFO] Worker exiting (pid: 20022) I have exported the SECRET_KEY correctly prior by doing '''export SECRET_KEY="my_key"''' This is what my settings.py looks like as well: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = False ALLOWED_HOSTS = ["my_ip"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project_name.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project_name.wsgi.application' DATABASES = { 'default': { … -
Simple way to implement Razorpay with Django
I want to know the simple and straight forward way to implement Razorpay's standard checkout method in my Django app. Consider a very basic scenario where the user just enters an amount in the form and the clicks on checkout and the Razorpay takes forward. -
Render date with url instead of calendar
I have a notebook where people can leave a note, they can set the note for later and find a note a request date. It is render as a calendar, I would like to have a link, for example, for the last 3 days and the next 3 days. I don’t where to begin. My views.py start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') set_start_date = None set_end_date = None if start_date and end_date: try: datetime.strptime(start_date, "%Y-%m-%d") datetime.strptime(end_date, "%Y-%m-%d") set_start_date = start_date set_end_date = end_date except: messages.error(request, _(f"The form is invalid")) return redirect('workspace-detail', token=token) My models.py class Notebook(models.Model): workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE, related_name='notes') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='author') message = models.CharField(max_length=3000, null=True, blank=True, verbose_name="Publier une note") date = models.DateTimeField(auto_now_add=False, null=False) -
Problem about sending email from Django, gmail blocks sign in from server
I am running website on scaleway server, 2 days ago i found "bug" which took 2 day to found out what was the problem, i am using email sending through django send_email, after 2 day of reviewing code found out that google blocks gmail sign in from scaleway server(which is located in Paris), is there anyway to somehow fix this problem? Thanks -
Rerun Query on Validation Failure
Here is my views.py. When the validation on the form fails, it returns you back to a blank board because my query cant be executed . What is the easiest way for me to rerun the query ? Thanks for the help ! @login_required def K8_Points_Classroom(request): #context_from_k8_points = request.session['k8_points_context'] if request.method == 'POST': form = K8Points_ClassroomForm(request.POST) if form.is_valid(): form.save(commit=False) form.save() class_name = form.cleaned_data.get('class_name') getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all() form = K8Points_ClassroomForm() context = {'form': form ,'students' : students, 'class_name': class_name,} messages.success(request,("Points were successfully added for student !")) return render(request,'points/k8_points_classroom.html', context) else: <--- Have to rereun query here so students will show again on redirect. messages.warning(request,(form._errors)) return render(request, 'points/k8_points_classroom.html', {'form': form} ) else: return render(request, 'points/k8_points_classroom.html', {'form': form} ) -
django rest_framework serializers inheritance
i'm Django new-bi my serializers code : class ProjectSerializer(serializers.ModelSerializer): class Meta: model = models.Projects fields = ('id', 'content', 'title', 'created') class TalkSerializer(serializers.ModelSerializer): class Meta: model = models.Talk fields = ('id', 'content', 'title', 'created') views code : class TalkViewset(viewsets.ModelViewSet): queryset = models.Talk.objects.all() serializer_class = serializers.TalkSerializer class ProjectViewset(viewsets.ModelViewSet): queryset = models.Projects.objects.all() serializer_class = serializers.TalkSerializer I think this method is too stupid. I want to reuse it as a class. What should I do? -
Email body sent in HTML
I am sending email from tinymce to all subscribed users using this view: def send_newsletter(request): form = NewsLetterEmailForm(request.POST or None) if form.is_valid(): instance = form.save() newsltr = NewsLetterEmail.objects.get(id=instance.id) print(newsltr.status) if newsltr.status == 'Published': subject = newsltr.subject body = mark_safe(newsltr.body) from_email = settings.EMAIL_HOST_USER for newsletter_obj in NewsLetter.objects.all(): send_mail(subject=subject, from_email=from_email, message=body, recipient_list=[newsletter_obj.email]) return render(request, 'newsletter/send-email.html', {'form': form}) but content of email is sent in html: <p><span style="font-family: 'arial black', sans-serif; font-size: 18pt;"><strong>Completely optimize efficient internal</strong></span></p> <p>or "organic" sources with fully tested schemas. Enthusiastically aggregate mission-critical infrastructures via top-line content. Objectively matrix cutting-edge bandwidth before viral action items. Objectively matrix viral users after sticky processes. Dramatically harness adaptive meta-services rather than scalable e-commerce.</p> I used mark_safe() method hoping it will work, but it didn't. How do I solve it? -
How can you filter model objects by attributes of their supermodel?
To get started with Django I did the intro provided by Django itself. In part 5 of it, you write some tests for views and models. After that, they provide you with ideas for more tests. There is where my problem starts. They suggest you to only show Questions with a number of Choices greater than 0. I have no idea how to do that. My current code can be found at https://github.com/byTreneib/django.git. The Django tutorial can be found at https://docs.djangoproject.com/en/3.0/intro/tutorial05/ -
Angular i18n integration with Django REST
Following those tutorials https://dev.to/angular/deploying-an-i18n-angular-app-with-angular-cli-2fb9 and https://devarea.com/building-a-web-app-with-angular-django-and-django-rest/ I manage to deploy angular within django. How can I rework the homePageView to serve index based on language? Expectation for internationalization: We will include a language prefix on each url that will tell Django which language to use. For the Home page it will be something like: myappsite.com/en myappsite.com/fr HomePageView class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) index.html {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>My App</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <!-- index.html --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script> <link rel="stylesheet" type="text/css" href="{% static 'fontawesome/css/all.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'styles.css' %}" /> </head> <body> <app-root>Loading...</app-root> <script src="{% static 'runtime-es2015.js' %}" type="module"></script> <script src="{% static 'runtime-es5.js' %}" nomodule defer></script> <script src="{% static 'polyfills-es5.js' %}" nomodule defer></script> <script src="{% static 'polyfills-es2015.js' %}" type="module"></script> <script src="{% static 'scripts.js' %}" defer></script> <script src="{% static 'main-es2015.js' %}" type="module"></script> <script src="{% static 'main-es5.js' %}" nomodule defer></script> </body> </html> -
how to update many to many fileds when i'm using request.post or get?
Lab Class class Lab(models.Model): laboratory = models.CharField(max_length=50, unique=True) group = models.ForeignKey(Lab_Group, on_delete=models.CASCADE) LabRequest Class class LabRequest(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) lab_test = models.ManyToManyField(Lab) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) This is how it looked like when I was saving data @login_required def LabRequestToGenerateView(request, pk): lab_group = '' doctor = Doctor.objects.filter(user_id=request.user.id, active='Yes') for doc in doctor: ticket = get_object_or_404( Ticket, pk=pk, has_cancelled=0, is_active=0, doctor=doc.id) lab_group = Lab_Group.objects.all() if request.POST.getlist('lab_test'): lab_test = request.POST.getlist('lab_test') laboratory = Lab.objects.filter(id__in=lab_test) lab_test_id = LabRequest.objects.filter(examined=0, paid=0, lab_test__in=lab_test, ticket__patient=ticket.patient.id) if lab_test_id: messages.success( request, 'Some lab tests have not been examined.') return redirect('/dashboard/lab-request') else: instance = LabRequest.objects.create( ticket=ticket, created_by=request.user.id) instance.lab_test.add(*laboratory) messages.success( request, 'Lab Request has been sent successfully.') return redirect('/dashboard/lab-request') context = { 'title': 'Laboratory Request', 'valueBtn': 'Save', 'lab_group': lab_group } return render(request, 'dashboard/laboratory_request.html', context) This is the way I'm trying to update LabRequest class but it's not complete because I have no idea how to update: @login_required def LabRequestUpdateView(request, pk): doctor = Doctor.objects.filter(user_id=request.user.id, active='Yes') for doc in doctor: lab_request_id = get_object_or_404(LabRequest, pk=pk, ticket__doctor=doc.id) context = { 'title': 'Update Request Lab', 'valueBtn': 'Update', 'lab_request_id': lab_request_id } return render(request, 'dashboard/laboratory_request.html', context) This is my template and I'm using the same template for saving data <form action="." method="POST"> {% csrf_token %} <div … -
Admin form to select existing object and related to existing object
I have a basket object, each basket could have many balls and a ball could be on many baskets, moreover each ball has many colors but one color is for one ball only. Models example: class Basket(models.Model): name = models.CharField(max_length = 100) class Ball(models.Model): basket = models.ManyToManyField(Basket, ) class Color(models.Model): ball = models.ForeignKey(Ball, on_delete = models.CASCADE) Each object has many other fields, not relevant I want in admin site when create a basket, select which ball and which color per ball. I tried inline, but it adds a new ball, i want just select existing ball and related color. PS:IMHO This is not a duplicate of this question because select Basket is covered but not select Color per ball. Thanks all -
JWT python Token Call in function
We are implementing authentication using OTP. And authorization using the JWT token. What we want to save is a call to API to fetch the bearer token. So we have a user with a user_name of 99999-99999. 1. And he sends a login request 2. We send him the OTP through SMS 3. He sends another request with the OTP for verification At this point as we have an event, we want to generate the token from JWT library and send it to the app -
What is the design handoff when working with Developers?
How can designers work with developers to deliver an excellent project? -
from django.contrib.auth.forms import UserCreationForm causing django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
So I see a lot of questions about the infamous "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." yet I cannot find anyone solving my problem as it doesn't have anything to do with my INSTALLED_APPS and it only goes away when I comment out the UserCreationForm.I am trying to create a basic signup page and UserCreationForm is the best way to do that. So does anyone know what I need to do to fix this? My lack of knowledge of this situation and of Django doesn't seem to help either but this seems as if it is a simple fix. Thank you for the help :). Here is all code I believe is relevant. In settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello.views',] urls.py from django.contrib import admin from django.urls import path from hello.views import myView from hello.views import myHome from hello.views import home from hello.views import index from hello.views import game from hello.views import main from hello.views import signup from django.contrib.auth import views as auth_views from django.views.generic.base import TemplateView from django.conf.urls import url, include urlpatterns = [ url(r'^admin/',admin.site.urls), url(r'^hello/',include('hello.urls')), path('sayHello/', myView), path('home/',home,name='Home'), path('game/',game,name="Game"), path('home/game.html',game), path('home/home.html',home), path('game/game.html',game), path('game/home.html',home), path('main/',main), path('signup/',signup, name="signup"), url(r'^login/$', auth_views.LoginView.as_view(template_name= 'login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(template_name= 'logged_out.html'), name='logout'), …