Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dj-rest-auth Reset email link keeps pointing to the backend
I'm using dj-rest-auth with react and i'm trying to use the frontend url instead of the backend url. The solution i am using for the account creation confirmation email affects the reset password email too but only partially. It does not effect the port. It only tries to add a key to the reset link where there is none and throws me an error. So i was wondering if there is a way to change the url from port 8000 to port 3000. This is what i have tried: class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request: HttpRequest): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) def send_mail(self, template_prefix, email, context): if settings.DEBUG: context["activate_url"] = ( "http://localhost:3000/accounts/confirm-email/" + context["key"] ) else: context["activate_url"] = ( settings.FRONTEND_URL + "/accounts/confirm-email/" + context["key"] ) return super().send_mail(template_prefix, email, context) If i get rid of the key part it doesn't give me an error but keeps port 8000 and breaks my account confirmation emails. If i don't get rid of the key it gives me: django | "http://localhost:3000/accounts/confirm-email/" + context["key"] django | KeyError: 'key' -
Django contenttypes follow/unfollow
Trying to use contenttypes to store following relations of users. I can create a follow, but I can't remove a follow from the database. Model Code accounts app ------------ from activities.models import Activity class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) follow = GenericRelation(Activity) activities app -------------- class Activity(models.Model) FOLLOW = 'F' LIKE = 'L' ACTIVITY_TYPES = [ (FOLLOW, 'Follow'), (LIKE, 'Like'), ] ## stores the user_id of the Liker/Follower user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ## stores 'F' or 'L' activity_type = models.CharField(max_length=2, choices=ACTIVITY_TYPES) date = models.ForeignKey(ContentType, on_delete=models.CASCADE) ## stores CustomUser id of the user who is followed or the id of the post that is liked object = models.UUIDField(null=True, blank=True, db_index=True) content_object = GenericForeignKey('content_type', 'object_id') class Meta: indexes = [models.Index(fields=["content_type", "object_id"]),] View Code follower = User.objects.get(id=follower_id) followed = User.objects.get(id=followed_id) ## This is the contenttypes model a = Activity.objects.filter(user=follower.id, object_id=followed.id) ## This is my janky way of checking whether the follower is already following the followed if len(a) == 0: ## This works to create a follow followed.follow.create(activity_type=Activity.FOLLOW, user=follower) I thought this might work to delete the follow followed.follow.remove(a) but it gives me an error 'QuerySet' object has no attribute 'pk' -
The current path, accounts/login/, didn't match any of these
Ive been trying to implement the reset password processs of django but something is not working, I know from the error that there is a url pattern that does not exit but from where accounts/login came from,It worked fine before but my colleague took my laptop and after that this happened urls.py """travel URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/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.contrib import admin from django.urls import path,include from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('',include('loginpage.urls')), path('signup/',include('signup.urls')), path('homepage/',include('Homepage.urls')), path('password_reset/',auth_views.PasswordResetView.as_view(template_name='loginpage/resetpassword.html'),name='password_reset'), path('password_reset_sent/',auth_views.PasswordResetDoneView.as_view(template_name='loginpage/password_resent_sent.html'),name='password_reset_done'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='loginpage/password_reset_form.html'),name='password_reset_confirm'), path('Password_changed_succesfully/',auth_views.PasswordResetConfirmView.as_view(template_name='loginpage/password_reset_done.html'),name='password_reset_complete') ] resetpassword.html: <!DOCTYPE html> <html> <head> {% load static %} <title>Reset Password</title> <link rel="stylesheet" type="text/css" href="{% static 'reset.css' %}"> <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css" /> </head> <body> <div class="right"><img src="{% static 'images/logo2.png' %}" height="400" width="400"></div> <div class="main"> <input type="checkbox" id="chk" aria-hidden="true"> <div class="resett"> <form … -
Iam Created Login Form but here If I login twice only it redirects the page in django
Here My Html Code I am created an Login Form Here my action is empty if I give an URL in action means. Then I will submit means it will goes to next page without authentication. Please Help me out...If I am login means it will redirect to the Page Dash. But here i want to login twice only means then it works successfully...If I login only once means it does'nt redirect the page I don't know why <form action="" method="post"> {%csrf_token%} <div class="form-outline mb-4"> <input type="text" name="username" id="form3Example3" class="form-control form-control-lg" class="form-control new-input" placeholder="Enter a Name" required> <label class="form-label" for="form3Example3"></label> </div> <div class="form-outline mb-3"> <input type="password" name="password" id="form3Example4" class="form-control form-control-lg" placeholder="Enter password" required> <label class="form-label" for="form3Example4"></label> </div> <div class="d-flex justify-content-between align-items-center"> <div class="form-check mb-0"> <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" /> <label class="form-check-label" for="form2Example3">Remember me</label> </div> <a href="#!" class="text-body">Forgot password?</a> </div> <div class="text-center text-lg-start mt-4 pt-2"> <input type="submit" value="submit" class="register-button2" /> </form> <p class="small fw-bold mt-2 pt-1 mb-0">Don't have an account? <a href="{% url 'register'%}" class="link-danger">Register</a></p> </div> Views.py def Login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: request.session['user'] = username auth.login(request,user) print(user) return redirect('Dash') else: messages.info(request,'invalid credientials') return redirect('Login') else: return render(request,'Login.html') This is the Dash View … -
Registration data "lost" somewhere in python django 4
I have my super basic authentication app, and I tried to write a simple Registration with email, first name, last name and (logically) password, but it seems that when I enter my request data it is "lost" somewhere. When I press the "POST" button, all the fields are blank and it says: "This field is required". I've been trying to figure it out for quite a long time, but I am new to django. I hope you can spot the problem. Here is my models.py: class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password=None): if first_name is None: raise TypeError('Users must have a first name') if last_name is None: raise TypeError('Users must have a last name') if email is None: raise TypeError('Users must have an email') user = self.model(email=self.normalize_email(email), first_name=first_name, last_name=last_name) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager My serializers.py: class RegistrationSerializer(serializers.ModelSerializer): token = serializers.CharField(max_length=255, read_only=True) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password', 'token'] def create(self, validated_data): return User.objects.create_user(**validated_data) And my views.py: class RegistrationAPIView(APIView): permission_classes = (AllowAny,) serializer_class = RegistrationSerializer def … -
How to add custom field when verifying access token in rest_framework_simplejwt
I tried to override validate method at TokenVerifySerializer but this raises AttributeError. from rest_framework_simplejwt.serializers import TokenVerifySerializer from rest_framework_simplejwt.views import TokenVerifyView class CustomTokenVerifySerializer(TokenVerifySerializer): def validate(self, attrs): data = super(CustomTokenVerifySerializer, self).validate(attrs) data.update({'fullname': self.user.fullname}) return data class CustomTokenVerifyView(TokenVerifyView): serializer_class = CustomTokenVerifySerializer But that does work when using TokenObtainPairSerializer and TokenObtainPairView. The above snippet raises AttributeError with 'CustomTokenVerifySerializer' object has no attribute 'user'. -
'settings.DATABASES improperly configured. Please Supply the ENGINE value' - when adding legacy database
I've added a second databases and i've connected it to apps via routers... all works well, i can access the data via the admin panel for the respective models and fields as specificied in my models.py in the apps.. perfect. One issue is when i run python manage.py migrate, I get an error saying django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Database code in settings.py: DATABASES = { 'default': { }, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'network_db':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'Network.sqlite3', }, 'simulation_db':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'Simulation.sqlite3', } } manage.py diffsettings command DATABASES = {'default': {'ENGINE': 'django.db.backends.dummy', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}}, 'auth_db': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': WindowsPath('C:/Users/backend/db.sqlite3')}, 'network_db': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': WindowsPath('C:/Users/backend/Network.sqlite3')}, 'simulation_db': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': WindowsPath('C:/Users/backend/Simulation.sqlite3')}} I've followed the documentation exactly which is how i've connected the legacy database and i'm able to access the data via admin panel.. however i am not sure what i'm doing wrong to cause the error when running python manage.py … -
Django / How to get the primary key from a specific field?
Models.py class scenes(models.Model): name = models.CharField('Event name', max_length=120) record_date = models.DateTimeField('Event date') Let's say I have recorded a scenes with name="world" In views.py, how can I query the pk from the name field ? from .models import scenes scene = scenes.objects.get('what should I put here to get the pk associated with name World ?') -
How can i use spreadsheets in your website
am trying to come up with a way to use spreadsheet in my website like i gather information from logged in users into the spreadsheet.any idea how iwill archive this or what tool to use or plugin in html .am using django as s backend language. -
'Page not found' error in Django code while making the pipeline
I am trying to make an e-commerce website in django. I want to lay the rough pipeline using this code but when i search, for example- http://127.0.0.1:8000/shop/about - This 404 Error come on my screen. Please tell me what to do. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/shop/about Using the URLconf defined in ekona.urls, Django tried these URL patterns, in this order: admin/ shop [name='ShopHome'] shop about [name='about'] shop contact/ [name='ContactUs'] shop tracker/ [name='Tracker'] shop search/ [name='Search'] shop prodview/ [name='ProdView'] shop checkout/ [name='Checkout'] blog The current path, shop/about, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. My settings.py is - """ Django settings for ekona project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
I have a structural problem with my user management code in django
I'm new to django. I'm trying to make a custom user management in django admin. I have an admin,py like this. """ from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms0 import UserCreationForm, UserAdminChangeForm from .models import User #from django.contrib import apps.authentication.models import apps.site.register(model) Register your models here. class UserAdmin(BaseUserAdmin): search_fields = ['employee', 'username'] add_form = UserAdminCreationForm form = UserAdminChangeForm list_display = ('username', 'employee', 'admin', 'staff', 'active') list_filter = ('admin', 'staff', 'active') """ It calls form0.py first before my model.py """ add_form = UserAdminCreationForm form = UserAdminChangeForm """ Models.py """ from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, UserManager class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, null=False, blank=False, verbose_name='Username') employee = models.OneToOneField('Employee', null=True, blank=True, verbose_name='Employee ID', related_name='user', on_delete=models.PROTECT) admin = models.BooleanField(default=False) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) """ form0.py """ from django import forms from django.db import models from .models import User class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'employee', 'admin', 'active', 'staff', 'groups') """ I get this error When I migrate it loads forms0 … -
DRF serializer's BooleanField returns null for empty ForeignKey field
I want to add boolean fields has_video and has_gallery to my serializer. Their values should be true if the ForeignKey fields of MyModel (video, gallery) have values, otherwise these values should be set to false. models.py class MyModel(models.Model): video = models.ForeignKey( to='videos.Video', null=True, blank=True, on_delete=models.SET_NULL, ) gallery = models.ForeignKey( to='galleries.Gallery', null=True, blank=True, on_delete=models.SET_NULL, ) serializers.py class MyModelSerializer(serializers.ModelSerializer): has_video = serializers.BooleanField(source='video', default=False) has_gallery = serializers.BooleanField(source='gallery', default=False) The problem occurs when the video or gallery value of MyModel object is null. I expect the returned values to be false but it is null. "has_video": null, "has_gallery": null, I try to set allow_null parameters to false but the result is the same (the values are still null). has_video = serializers.BooleanField(source='video', default=False, allow_null=False) has_gallery = serializers.BooleanField(source='gallery', default=False, allow_null=False) When the video or gallery is not null, the serializer's fields return true as I expect. The problem is just about null/false values. -
Uncaught ReferenceError: $ is not defined in Javascript
i am getting this error message when trying to submit a form in django using ajax i cannot really tell what is bringing up this error. i have tried many solutions but they dont seem to be working as expected. this is the exact error showing up in my console csrfmiddlewaretoken=tHTBQbePA8SQrkk9SL18uCsPCIYLE5rey9dFd8vKUhlQDYbh2vLNC5Y5gl3QNXue&full_name=&bio=&email=&phone=:39 Uncaught ReferenceError: $ is not defined at ?csrfmiddlewaretoken=tHTBQbePA8SQrkk9SL18uCsPCIYLE5rey9dFd8vKUhlQDYbh2vLNC5Y5gl3QNXue&full_name=&bio=&email=&phone=:39:7 index.html <title>Django Form Submission</title> </head> <body> <div class="container"> <h1 class="text-center mt-5">Create Profile</h1> <h5 class="text-success text-center"></h5> <form class="container mt-5" id="post-form"> {% csrf_token %} <div class="mb-3 mr-5 "> <input type="text" class="form-control" id="full_name" name="full_name" placeholder="Full Name"> </div> <div class="mb-3 mr-5 "> <input type="text" class="form-control" id="bio" name="bio" placeholder="Bio"> </div> <div class="mb-3 mr-5 "> <input type="email" class="form-control" id="email" name="email" placeholder="Email Address"> </div> <div class="mb-3 mr-5 "> <input type="text" class="form-control" id="phone" name="phone" placeholder="Phone"> </div> <button type="submit" class="btn btn-success">Submit</button> </form> </div> <script type="text/javascript"> $(document).on('submit', '#post-form', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/create', data: { full_name: $('#full_name').val(), bio: $('#bio').val(), email: $('#email').val(), phone: $('#phone').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function (data) { ("h5").html(data) } }) }) </script> </body> </html> views.py from django.shortcuts import render from core.models import Profile from django.http import HttpResponse def index(request): return render(request, 'index.html') def create(request): if request.method == 'POST': full_name = request.POST['full_name'] bio = request.POST['bio'] … -
Serialization Issue Django in filefield
I have an issue when I am trying to get the list of my stored data in Django. Output: {name:/filename, evaluation: "not evaluated"} I am able to get my database content, but I have a "/" before each name value. My question is: How can I do to remove this /? Here is a copy of my code. Thanks for your help class myModel(models.Model): name=models.FileField(storage=fs) evaluation=models.CharField(max_length=256,default="Not evaluated") def list(self, request, *args, **kwargs): queryset = myModel.objects.all() serializer = mySerializer(queryset, many=True) return Response(serializer.data) class mySerializer(serializers.ModelSerializer): class Meta: model = myModel fields = ('name','evaluation') -
I want to assign value of logged in user's user_company to the user_company field of the newly created user
When a user creates a user record for a client, the new client should should have the current logged in user's User.user_company value. In the problem here, I want to assign the value of the logged in user's User.user_company into the new user's clientuser.user_company when save() is called in the view. here is the serializer below with the clientuser object. class ClientSerializers(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) client_name = serializers.CharField(style={'input_type' : 'text'}, required=True) class Meta: model = User fields = ['email', 'username', 'password', 'password2', 'user_type', 'client_name'] extra_kwargs = { 'password': {'write_only': True}, #dont want anyone to see the password 'user_type': {'read_only': True}, } def save(self): clientuser = User( #creating a user record. it will record company fk email=self.validated_data['email'], username=self.validated_data['username'], user_type = 3, first_name = self.validated_data['client_name']) #validating the password password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: #trying to match passwords. raise serializers.ValidationError({'password': 'Passwords must match.'}) clientuser.set_password(password) #setting the password clientuser.save() #saving the user return clientuser I've tried using cur_usr = User() param = 'user_company' usr_comp = getattr(u, param) print(f'usr_comp is {usr_comp}) print statement prints usr_comp is None in the terminal I've also tried using curr_User_Company = User.user_company user.user_company = curr_User_Company it returns the following line in the terminal … -
Where to store database used in Django project?
I am developing a personal website using Django (to learn). I want to also save it on GitHub. Where to store the database [file] itself? Not on GitHub? If I want to make a save a copy of the database in case it vanishes, where does one typically upload their database? If my website is a "production" website with enough content, what would be the best practice? -
python framework for trading robot
I want to create a web application for trading. Front - React Backend - Python I can't decide which Python framework to choose. Backend should accept a request from the front, make a request to a third-party API and return its response to the front. Also, there is analytics module on the backend, which performs operations with data from API and front and sends requests to API too. A heavy load is assumed and the speed of work is critical for the application. I don't need a lot of models and admin panel. I choose between django, flask, FastApi, but if there are other frameworks for this task, I will be glad to hear. What would you recommend? Interested in the simplest solution to these problems. -
Got multiple values for argument 'Pattern' in Django
This is an 7 year old Django website and I'm trying to migrate it to the latest python version and got an error Error urls.py line 13, in urlpatterns = [ path('CyberHealth.views', TypeError: _path() got multiple values for argument 'Pattern' This is my urls.py urlpatterns = [ path('CyberHealth.views', path('', views.index, name='index'), #==== Role === path(r'^getorinsertroleAPI/$', views.getorinsertroleAPI, name='getorinsertroleAPI'), path(r'^updateordeleteroleAPI/(?P<pk>[0-9]+)/$', views.updateordeleteroleAPI, name='updateordeleteroleAPI'), #==== Register === path(r'^registerUser/$', views.registerUser, name='registerUser'), path(r'^registerFBUser/$', views.registerFBUser, name='registerFBUser'), path(r'^admin/registerCoach/$', views.reg -
Allow users to comment using their social media profiles
I am developing a personal blog using Django (to learn). I want to be the only user that is allowed to post there. However, I want to allow people to comment on my posts, when they do not register but (not sure of the correct terminology here) log in via their Google etc account to place a post. How is this functionality called? How can I achieve this in Django? Do I need to still save the user credentials etc into the database? Do I still need to have a Comment model (I think so)? -
Creating docker container with tensorflow giving libcublas.so error
I created a docker container with the Django app, celery, redis for database used Postgres. While we are importing tensorflow it is giving error of Libssl.so not found where as the file is exist in the docker container itself. Python = 3.6.12 Tensorflow-gpu=1.12.0 cuda = 9.0 cudnn = 7 The docker-compose.yml file which we are using are: version: '3' services: web: volumes: - static:/static - /usr/local/cuda/lib64/:/usr/local/cuda/lib64/ - /usr/lib/x86_64-linux-gnu/:/usr/lib/x86_64-linux-gnu/ - /usr/lib/nvidia-410/:/usr/lib/nvidia-410/ build: context: . ports: - "8000:8000" networks: - nginx_network hostname: "web" nginx: build: ./nginx volumes: - static:/static ports: - "3333:3333" networks: - nginx_network depends_on: - web hostname: "nginx" db: image: postgres:13.0-alpine container_name: ps01 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=AVL^&*() - POSTGRES_DB=xtract_prod networks: nginx_network: volumes: static: Docker File is: FROM alpine:latest FROM python:3.6.12 ENV LANG=C.UTF-8 RUN pip install --no-cache-dir --upgrade pip #LC_ALL=C.UTF-8 # FROM python:3.5.2 # RUN apt-get install libssl1.1 # RUN export LD_LIBRARY_PATH=/home/xaltgpu/miniconda3/lib RUN echo "/home/xaltgpu/miniconda3/lib" > /etc/ld.so.conf.d/openssl.conf RUN ldconfig RUN echo 'export LD_LIBRARY_PATH=/usr/local/cuda/extras/CUPTI/lib64:/usr/local/cuda/lib:/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu:/usr/lib/nvidia-430' >> ~/.bashrc #RUN nvidia-smi RUN apt-get install libssl-dev libffi-dev -y RUN apt-get update RUN apt-get install libidn2-0 RUN apt-get install ffmpeg libsm6 libxext6 -y COPY temp_1 /app/temp_1 COPY entrypoint.sh app/entrypoint.sh COPY req.txt /app/req.txt WORKDIR /app RUN pip install -r req.txt RUN ls RUN pwd … -
Wagtail panel for self-referential many to many relationships with a through model
I am busy making something like a knowledge graph in wagtail. CurriculumContentItem is a node on that graph. It has a many-to-many relationship with itself, and the through model has important fields. I'm struggling to get this to be usable in the admin page. Please see the inline comments: class ContentItemOrder(models.Model): post = models.ForeignKey( "CurriculumContentItem", on_delete=models.PROTECT, related_name="pre_ordered_content" ) pre = models.ForeignKey( "CurriculumContentItem", on_delete=models.PROTECT, related_name="post_ordered_content" ) hard_requirement = models.BooleanField(default=True) class CurriculumContentItem(Page): body = RichTextField(blank=True) prerequisites = models.ManyToManyField( "CurriculumContentItem", related_name="unlocks", through="ContentItemOrder", symmetrical=False, ) content_panels = Page.content_panels + [ # FieldPanel("prerequisites") # FieldPanel just lets me select CurriculumContentItems, but I need to access fields in the through model # InlinePanel("prerequisites"), # This causes a recursion error FieldPanel('body', classname="full collapsible"), ] If I wanted to do this in the normal Django admin I would make use of an inlines to specify prerequisites. Something like: class ContentItemOrderPostAdmin(admin.TabularInline): model = models.ContentItem.prerequisites.through fk_name = "post" class ContentItemOrderPreAdmin(admin.TabularInline): model = models.ContentItem.unlocks.through fk_name = "pre" Is there a similar mechanism in Wagtail? It looks like I need to create a custom Panel for this. -
Is it possible to allow to create objects from the list_display view of the django admin site?
I have a model with fields name, roll_no, birth_date I am using the django admin's list display and list editable to have these fields displayed and edited in a list format in a single page. However, to add a new entry I have to go to the create_form page. Is it possible to simply add new objects from the list_display page itself? -
Populate selectbox after div show with columns from a pandas dataframe
So, I have a html form which, after submit, populates some selectboxes with rows values form a pandas dataframe. I have added a jquery script in order to hide the selectboxes before submit and show after submit , but the selectboxes are not being populated anymore as before. For sure something is missing but unfortunately I am pretty new to js and jquery. This is my script: $(document).ready(function(){ $("#myform").submit(function(e) { e.preventDefault(); $("#second").show(); }); This is my html: <form method = "POST" action ="dashboard" id="myform"> {% csrf_token %} <select name="line"> <option value=" 1" selected="selected"> 1</option> <option value=" 2">2</option> <option value=" 3">3</option> <option value="All">ALL</option> </select> Line <select name="data"> <option value="weekly" selected="selected">weekly</option> <option value="monthly">monthly</option> </select> Data <input type="submit" value="Select"> </form> </div> <div id = "second" style="display:none"> <br><br><br> <select class="position"> {% for pos in posnr %} <option value="{{ pos }}">{{ pos }}</option> {% endfor %} </select> <select class="x"> {% for pos in posnr %} <option value="{{ pos }}">{{ pos }}</option> {% endfor %} </select> <select class="y"> {% for pos in posnr %} <option value="{{ pos }}">{{ pos }}</option> {% endfor %} </select> </div> This is part of a django project , the view part is working well -
Other websockets does not work when a websocket is pending
I use Django Channels and I have multiple websocket addresses. When I connect to a websocket, it gets and computes somethings from database and this process may take 10 seconds. But during this 10 seconds all of my websockets does not respond to any user and it yields a 502 Bad Gateway to every user. It seems that all of my websockets are running by a single agent, and when it is pending, all other websockets does not respond anymore, until the agent becomes free. My code is some like the following code. How can I solve this problem? class SymbolConsumer(WebsocketConsumer): def connect(self): self.symbol_name = self.scope["url_route"]["kwargs"]["symbol_name"] async_to_sync(self.channel_layer.group_add)(self.symbol_name, self.channel_name) self.accept() self.send(time_consuming_function_1(self.symbol_name)) self.send(time_consuming_function_2(self.symbol_name)) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.symbol_name, self.channel_name ) def receive(self, text_data): pass -
AttributeError: module 'django.db.models' has no attribute 'Textfield'
am trying to run my python manage.py makemigrations in my terminal but it is giving me this error File "/home/collins/Dev/trydjango/src/products/models.py", line 5, in Product title = models.Textfield() AttributeError: module 'django.db.models' has no attribute 'Textfield' what could be the problem?