Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Faster way than .csv to upload data into Django app
Right now I copy a whole table from a website, paste it into a cell on an excel spreadsheet and it formats it into a .csv file. After the .csv is made I upload the file into my database via a Django app. I also have a model form if I wanted to enter the data manually. What I was wondering is if there is a way to skip a step to make the process faster. Maybe copy the table from the web and paste it into a form cell and it gets formatted like excel does. Any tips or ideas are greatly appreciated. -
accessing 2 foreign key fields at the same time in django serializers
I have the following models in my django rest framework project. in this project there are products and they have producers and importers. # models.py class Product(models.Model): name = models.CharField(max_length=255) producer = models.ManyToManyField(Company, related_name='producer') importer = models.ManyToManyField(Company, related_name='importer') class Company(models.Model): name = models.CharField(max_length=255) I need to make an API which retrieves an instance of the "Company" model and gives me a list of the products they have produced and another list for the products that they have imported Now I know to do this with only one manytomany field, I can do the following: class CompanyRetrieveSerializer(serializers.ModelSerializer): class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('name',) product_set = ProductSerializer(read_only=True, many=True,) class Meta: model = Company fields = '__all__' but since there are two fields in the product model that reference the company model, this doesn't work. Is there any way to fix this issue? -
Why isn't my javascript not working with django
I am a beginner in django. I have no problem with the back-end but my front-end has some problem with javascript (specifically addEventListener doesn't work). I've tried everything from adding External js to adding internal js nothing seems to work. But the js connect with django and its being loaded, but the function doesn't work and no error seems to log in the console. It is just a click function, which should toggle a classname in html while clicked. By the way I'm inheriting my nav file. i hope that doesn't cause any problem. My internal js file: <script type="text/javascript"> // EVENT LISTENER FOR NAV FUNCTION let nav_btn = document.querySelector('.user-pr') nav_btn.addEventListener('click', navfunc) function navfunc() { nav_btn.classList.toggle('active') console.log("click") } </script> My Settings.py file (Static Config): STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'Assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I've checked StackOverflow for similar questions, but nothing match my scenario. -
404 Not Found nginx/1.18.0 (Ubuntu) when deploying django in aws
I'm trying to deploy a django project on aws using nginx server any (and aws RDS mysql database). After configuration I'm getting 404 Not Found nginx/1.18.0 (Ubuntu) error. When I try to access any the pages of the application except the url for the home page (/). That's, I can access only the base url, others are showing page not found root /var/www/html; # Add index.php to the list if you are using PHP index index.php index.html index.htm index.nginx-debian.html; server_name ip_address; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. include proxy_params; proxy_pass http://unix:/var/www/html/django/app.sock; try_files $uri $uri/ =404; } # pass PHP scripts to FastCGI server location /phpmyadmin/{ root /usr/share/; index index.php; try_files $uri $uri/ =404; } location /static/ { autoindex on; alias /var/www/html/django/staticfiles/; proxy_pass http://unix:/var/www/html/django/app.sock; try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; # # # With php-fpm (or other unix sockets): fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # # With php-cgi (or other tcp sockets): # fastcgi_pass 127.0.0.1:9000; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } } I developed the … -
How to set celery in docke-compose.yml
I am trying to integrate celery, rabbitmq with my django app and run it using docker, below is my docker-compose.yml file: version: '3.4' services: db: image: postgres:13.4 env_file: - ./docker/env.db ports: - 5432:5432 app: &app build: context: . dockerfile: ./docker/Dockerfile env_file: - ./docker/env.db - ./.env volumes: - .:/opt/code ports: - 8000:8000 - 3000:3000 depends_on: - db - rabbitmq command: bash ./scripts/runserver.sh rabbitmq: image: rabbitmq:3.7-alpine container_name: 'rabbitmq' ports: - "5672:5672" celery: <<: *app command: celery -A app worker --loglevel=info ports: [] depends_on: - rabbitmq However,I am getting this error: celery_1 | [2022-01-22 07:03:36,373: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. celery_1 | Trying again in 6.00 seconds... (3/100) What should I do? Help would be much appreciated. Thank you! -
Django Pass through Table field data to Serializer
I have the following models: class Disease(models.Model): name = CICharField("Disease Name", max_length=200, unique=True) symptoms = models.ManyToManyField(Symptom, through='DiseaseSymptom', related_name='diseases') class Symptom(models.Model): name = CICharField("Symptom Name", max_length=200, unique=True) PRIORITY = ( (0, 'Normal'), (1, 'Low'), (2, 'Medium'), (3, 'High'), (4, 'Key'), ) class DiseaseSymptom(models.Model): disease = models.ForeignKey(Disease, on_delete=models.CASCADE, related_name='disease_to_symptom') symptom = models.ForeignKey(Symptom, on_delete=models.CASCADE, related_name='symptom_to_disease') priority = models.PositiveSmallIntegerField('Priority', choices=PRIORITY, default=0) On the front-end, I have multiple select boxes where users can select multiple Symptoms to find disease and that will pass to Disease model as symptoms_selected params. I have the following get_queryset on Disease > views.py def get_queryset(self): params = self.request.query_params query_symptoms = self.request.GET.getlist('symptoms_selected') if query_symptoms: queryset = Pattern.objects.filter( symptoms__id__in=query_symptoms ).annotate( matches=Count('symptoms') ).order_by('-matches') else: queryset = Disease.objects.all() return queryset serializer_class = DiseaseSerializer I am using Django REST API to pass the result data. class DiseaseSerializer(serializers.ModelSerializer): symptoms_matches = serializers.SerializerMethodField() class Meta: model = Disease fields = ('id', 'name','symptoms_matches') def get_symptoms_matches(self, obj): return getattr(obj, 'matches', None) For eg: Disease Data: Disease A: Got Symptoms: A (priority=4), B (priority=2), C (priority=3), D (priority=2) Disease B: Got Symptoms: A (priority=1), D (priority=2), P (priority=4), Q (priority=2) Currently, if Users select 2 symptoms: A, D. I want queryset will return the count of key symptoms matched i.e. symptom … -
I have 2 forms on the same page that uses django-recaptcha ReCaptchaV2Invisible, when I submit the "2nd" form the "1st form is submitted instead
Hi I have two forms on my home page, the one is a "contact form" and the other one is a "subscribe to mail list form". I used the "django-recaptcha ReCaptchaV2Invisible" field on both forms. The contact form works fine, but if I submit the second form (the mail list one) the first form is submitted and I get and invalid form error (obviously). Has anyone experience the same problem? any recommended fixes? Thanks -
Google Cloud Django Postgres: could not connect to server: Connection refused
I've deployed a Django project to Google App Engine Flexible Environment and using postgress for database connection. I followed this https://cloud.google.com/python/django/flexible-environment I've successfully setup it on my local machine but when I deploy on cloud I'm getting following error: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Here is my database setup in my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': '/cloudsql/INSTANCE_CONNECTION_NAME', 'NAME': 'DB_NAME', 'USER': 'DB_USERNAME', 'PASSWORD': 'DB_PASSWORD', 'PORT': '5432', } } when I start server in local db: ./cloud_sql_proxy -instances="PROJECT_NAME:REGION:INSTANCE_NAME"=tcp:5432 I get this : Listening on 127.0.0.1:5432 for PROJECT_NAME:REGION:INSTANCE_NAME"=tcp:5432 and when try on local i tried like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': '/cloudsql/INSTANCE_CONNECTION_NAME', 'NAME': 'DB_NAME', 'USER': 'DB_USERNAME', 'PASSWORD': 'DB_PASSWORD', 'PORT': '5432', 'HOST': '127.0.0.1' } This works on my local computer and I can access DB. but when I remove 'HOST': '127.0.0.1' for deployment. after deployment I'm getting connection refused error -
IntegrityError at /apis/addtoCart NOT NULL constraint failed Django and API?
i am trying to insert data into my OrderItem() model: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) with an api with json data as follows: { "username": "admin", "item": "Kavya", "quantity": "1" } and i my view i am recieving this data and updating like: class addtoCart(APIView): # permission_classes=[IsAuthenticated,] # authentication_classes=[TokenAuthentication,] def post(self,request): username=request.data["username"] itemname=request.data["item"] quant=request.data["quantity"] #inserting data to cart article = OrderItem() article.User = username article.Item = itemname article.quantity=quant article.save() query=OrderItem.objects.filter(user=username) serializers=OrderItemSerializer(query,many=True) return Response(serializers.data) but whenever i try to do so i get an error: IntegrityError at /apis/addtoCart NOT NULL constraint failed: core_orderitem.item_id i dont know what causing this error can someone please help <3. -
How to use proxy with vite (vue frontend) and django rest framework
So, you know when you access a view with django rest api on the browser, you get an html page, and when you send something like an ajax request, you get the json? I'm trying to figure out how to mess with the proxy setting for vite, but I can't find a single decent documentation around it. I want to redirect '/' to 'http://localhost:8000/api', but there's really weird behavior going on. If I do this: //vite.config.js export default defineConfig({ plugins: [vue()], server: { proxy: { '/api': { target: 'http://localhost:8000', changeOrigin: true, rewrite: (path) => { console.log(path); return path.replace('/^\/api/', '') } } } } }) //todo-component.vue export default { data() { return { todos: [] } }, components: { TodoElement }, beforeCreate() { this.axios.get('/').then((response) => { this.todos = response.data }) .catch((e) => { console.error(e) }) } } and make requests using '/api', it works as expected. However, if I do export default defineConfig({ plugins: [vue()], server: { proxy: { '/': { target: 'http://localhost:8000/api', changeOrigin: true, rewrite: (path) => { console.log(path); return path.replace('/^\/api/', '') } } } } }) import TodoElement from "./todo-element.vue" export default { data() { return { todos: [] } }, components: { TodoElement }, beforeCreate() { this.axios.get('/').then((response) => … -
fetching data from firebase and displaying in django templates (in table format)
hello am new to firebase i just want to fetch data from firebase and display in django(in table) db look like: enter image description here code in view.py look like: enter image description here code in html look like enter image description here o/p look like while running sever enter image description here please help me out by: displaying n no of node in templates in table format -
Is there a a function to implement when dealing with django image or filefield? Please help me out
I create a filed which contain Imagefield in my models but when I am trying to add the image to the to the field in my admin page it is telling me function not implemented This is how my models look like from django.db import models # Create your models here. class Image(models.Model): name = models.CharField(max_length = 40) img = models.ImageField(upload_to = 'images/') def __str__(self): return self.name This is my root MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And this is the exception I got anytime I try to upload image to the models in my admin page OSError at /admin/imageapp/image/add/ [Errno 38]Function not implemented Request. Method: POSTRequest. URL:http://127.0.0.1:8000/admin/imageapp/image/add/ DjangoVersion:3.2.11 Exception Type:OSError Exception Value:[Errno 38] Function not implemented Exception. Location:/data/data/com.termux/files/home/ imagetest/lib/python3.10/ site-packages/django/core/files/locks.py, line 117, in unlockPython. Executable:/data/data/com.termux/files/home/imagetest /bin/pythonPython Version:3.10.2Python Path: ['/storage/emulated/0/imagetest', '/data/data/com.termux/files/usr/lib/python310.zip', '/data/data/com.termux/files/usr/lib/python3.10', '/data/data/com.termux/files/usr/lib/python3.10/lib- dynload', '/data/data/com.termux/files/home/ imagetest/lib/python3.10/site-packages'] Server time:Fri, 21 Jan 2022 16:13:45 +0000 -
Can't save chat messages with django and websocket
So I've been following this tutorial to build a chat feature between two users using Django and WebSockets/Channels: https://www.youtube.com/watch?v=lHGcSOkrKw0&t=122s&ab_channel=AaravTech Everything seems to work fine except for saving the chat messages. When I refresh the page the chat disappears. From checking the database, the thread instance is created but nothing is saved into it. It is just an empty {}. The thread instance can be called and has an ID. No new thread instance is created when I am trying to connect with a user with whom I already connected. app_chat/managers.py from django.db import models from django.db.models import Count class ThreadManager(models.Manager): def get_or_create_personal_thread(self, user1, user2): threads = self.get_queryset().filter(thread_type='personal') threads = threads.filter(users__in=[user1, user2]).distinct() threads = threads.annotate(u_count=Count('users')).filter(u_count=2) if threads.exists(): return threads.first() else: thread = self.create(thread_type='personal') thread.users.add(user1) thread.users.add(user2) return thread def by_user(self, user): return self.get_queryset().filter(users__in=[user]) app_chat/models.py from django.db import models from app_users.models import User from app_chat.managers import ThreadManager class TrackingModel(models.Model): created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField( max_length=15, choices=THREAD_TYPE, default='group') users = models.ManyToManyField(User) objects = ThreadManager() def __str__(self): if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' … -
Django CBV template ignores the override
First, settings.py set url conf: ROOT_URLCONF = "myproject.urls" , and INSTALLED_APPS includes: "myproject.apps.accounts", , which, in turn, has its urls.py set up with: app_name = "accounts" and path("login/", auth_views.LoginView.as_view(template_name="accounts/login.html", form_class=UserLoginForm), name="login"), manage.py check doesn't report any problems, and yet both routes don't work, though But browser reports on route of :accounts/login' reports: TemplateDoesNotExist at /accounts/login/ registration/login.html , where the name it misses is not the one I've put in template_name. I see this in the docs: template_name: The name of a template to display for the view used to log the user in. Defaults to registration/login.html. , which is why I'm overriding, right?... What am I doing wrong? Thanks! -
Django ManyToMany field object automatically pre-fills
I have an PaypalOrder model that is created when someone orders from a website, and it has a ManyToManyField that connects it to multiple OrderItems. Whenever I create a PaypalOrder, it automatically lists every OrderItem that exists in the django admin panel. How do I only list the objects that I set it to connect to? my models.py: class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() is_a_subscription = models.BooleanField(default=False) subscription = models.ForeignKey('Subscription', on_delete=models.CASCADE, null=True, blank=True) class PaypalOrder(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) items_and_quantities = models.ManyToManyField(OrderItem, blank=True, related_name="paypalorder") full_name = models.CharField(max_length=100) address1 = models.CharField(max_length=250) address2 = models.CharField(max_length=250, null=True, blank=True) city = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) total_paid = models.DecimalField(max_digits=10, decimal_places=2) order_id = models.CharField(max_length=100, null=True, blank=True) subscription_id = models.CharField(max_length=100, null=True, blank=True) email=models.CharField(max_length=100, null=True) country_code = models.CharField(max_length=100) state = models.CharField(max_length=50, null=True) my view: order = PaypalOrder.objects.create( user = user, full_name= resp['subscriber']['name']['given_name'] + " " + resp['subscriber']['name']['surname'], email = resp['subscriber']['email_address'], city = resp['subscriber']['shipping_address']['address']['admin_area_2'], state = resp['subscriber']['shipping_address']['address']['admin_area_1'], address1 = resp['subscriber']['shipping_address']['address']['address_line_1'], address2 = addr2, zipcode = resp['subscriber']['shipping_address']['address']['postal_code'], country_code = resp['subscriber']['shipping_address']['address']['country_code'], total_paid = resp['billing_info']['last_payment']['amount']['value'], order_id = "product_ID: " + resp['id'], subscription_id = resp['plan_id'], created_at = resp['create_time'], ) order.save() subscription = Subscription.objects.create(user = request.user, paypal_order = order) order.items_and_quantities.set(OrderItem.objects.filter(pk=100)) -
How to get required fields as a list of json by DRF serializer
I am trying to acieve simple nested json. serializer.py class CurrencyMasterSerializer(serializers.ModelSerializer): class Meta: model = CurrencyMaster fields = ["id", "name"] { "id": 1, "name": "USD - United States Dollar" }, { "id": 2, "name": "EUR - Euro Members" }, { "id": 3, "name": "JPY - Japan Yen" }, This is I got response by postman. But I expect output like below, { "country-codes": [ { "id": 1, "name": "USD - United States Dollar" }, { "id": 2, "name": "EUR - Euro Members" }, { "id": 3, "name": "JPY - Japan Yen" }] } How can i achieve this???? -
How to access request data in Nested Serializer?
I am trying to create writable nested serializer to create posts. I want to create multiple model instances of Image and Video. However, I don't know how to access request.data in the nested serializer which is necessary for the many=True condition #serializers.py class PostSerializer(serializers.ModelSerializer): images = ImageViewSerializer(many=True) videos = VideoViewSerializer(many=True) class Meta: model = Post fields = ['caption', 'user', 'images', 'videos'] extra_kwargs = { 'caption': {'required': False}, 'images': {'required': False}, 'videos': {'required': False} } def create(self, validated_data): return super().create(validated_data) I want to make it like so... class PostSerializer(serializers.ModelSerializer): images = ImageViewSerializer(many=isinstance(request.data,list)) videos = VideoViewSerializer(many=isinstance(request.data,list)) ... -
DJANGO Beginner to Intermediate
I'm new to the Django Project and Community Can someone recommend me any YT channels or Books for pursuing in Django? -
Unknown field(s) (username) specified for Account. Check fields/fieldsets/exclude attributes of class AccountAdmin
Ive been spending hours on figuring out how to fix this error however I can figure it out? I have specified the different fields. This occurs when im in the admin panel and i try to add a new account - SNI works fine. I dont understand. Am i missing something? I have set the user field too Model from asyncio import FastChildWatcher import email from pyexpat import model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=10, primary_key=True) # USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(max_length=80, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Admin from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Account, sni class AccountAdmin(UserAdmin): ordering … -
Django Assigning users to models
I'm trying to create an assigning feature to my blogapp in Django What I want to do is when a new user is created, that user automatically gets added to an Assign Model, which you would then be able to assign a person(s) from a dropdown menu to whatever blog a user chooses. Here's my code so far 'models.py' class Assign(models.Model): name = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class Issue(models.Model): MARK_AS = ((True, 'Open'), (False, 'Closed')) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Assign, on_delete=models.SET_NULL, null=True) mark_as = models.BooleanField(choices=MARK_AS, default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) 'views.py' class IssueCreateView(LoginRequiredMixin, CreateView): model = Issue fields = ['title', 'content', 'mark_as', 'assignee'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class IssueUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Issue fields = ['title', 'content', 'mark_as', 'assignee'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): issue = self.get_object() if self.request.user == issue.author: return True return False -
How to stop Django from evaluating false template conditions?
I have a Django template that renders links defined by specific apps like: <div>{% url 'admin:myapp_myview' %}</div> However, I want to make this app optional in my code, so I created a simple tag, called is_installed, like: import logging from django.apps import apps logger = logging.getLogger(__name__) @register.simple_tag def is_installed(name): result = apps.is_installed(name) logger.info('App "%s" is installed? %s', name, result) return result and use that to wrap my link in an if statement like: {% load mytags %} {% is_installed "myapp" as is_myapp_installed %} {% if is_myapp_installed %} <div>{% url 'admin:myapp_myview' %}</div> {% endif %} Unfortunately, it looks like regardless of the value of is_myapp_installed, Django's template engine evaluates all parts of the template, even if those parts are wrapped in if statements with false conditions. This means that when I disable myapp from my INSTALLED_APPS list, I see my log output: App "myapp" is installed? False Yet Django gives me the template error: Reverse for 'myapp_myview' not found. 'myapp_myview' is not a valid view function or pattern name. implying it's ignoring the if statement. Is there any way to fix this and stop Django from evaluating code inside false if statements? Are there alternative solutions? -
Bootstrap Navbar Logo not found
Hello I am trying to get my NavBar on bootstrap to show a Logo, I have tried moving the png to different folders in the app but I get this error: System check identified no issues (0 silenced). January 21, 2022 - 18:18:54 Django version 4.0.1, using settings 'mapproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [21/Jan/2022 18:19:00] "GET / HTTP/1.1" 200 229230 Not Found: /logo.png [21/Jan/2022 18:19:00] "GET /logo.png HTTP/1.1" 404 2219 Here is the index.html: <!--Navbar--> <!-- Just an image --> <!-- Image and text --> <nav class="navbar navbar-dark bg-dark"> <a class="navbar-brand" href="#""> <img src="logo.png" width="30" height="30" class="d-inline-block align-top" alt=""/> EtherWAN Product Map </a> </nav> <!--End Navbar--> -
How do I customize django allauth sign up forms to look the way I want?
How do I make a registration form without using this code <form class="signup" id="signup_form" method="post" action="{% url 'account_signup'}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} »</button> </form> Here is a small snippet of the custom sign up html <div class="group-35"> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup'}"> {% csrf_token %} <div class="overlap-group-container-1"> <input class="overlap-group1 border-1px-dove-gray -applesystemuifont-regular-normal-black-20px" type="text" id="first_name" name="first_name" placeholder="First Name"/> <input class="overlap-group2 border-1px-dove-gray -applesystemuifont-regular-normal-black-20px" type="text" id="last_name" name="last_name" placeholder="Last Name"/> </div> <div class="overlap-group"> <input class="rectangle border-1px-dove-gray -applesystemuifont-regular-normal-black-20px" type="email" id="email" name="email" placeholder="Email"/> </div> This code was generated using anima and I want to use input fields to sign up the user. So from this snippet I'd want to sign the user up with the first name, last name and email they entered in the input fields. -
How do I call custom Django Model Manager from Class Based View?
I would like to use a customer model manager that manipulates a field but does not save to the database. How do I call the model manager function named "with_counts()" in the sample code below. Is it possible to call it from my view or my templates? LEVEL = [ ('Pro', 'Professional'), ('Int', 'Intermediate'), ('OK', 'Competent') ] Languages = models.CharField(max_length=25) Years = models.IntegerField(default=1) Proficiency = models.CharField(max_length=15, choices=LEVEL, default="Competent") def __str__(self): return f'{self.Languages} Level: {self.Proficiency}' #Do not save to data base. def with_counts(self): return self.years * 10; -
NextJS/Django Manually Typing in URLs
I'm trying to set up an application that uses Django on the backend and NextJS on the front end. I've set this up by statically exporting the NextJS app then Django app handles routing and uses index.html as a catch all for any routes it does not know. This is working relatively well however I am running into a routing issue with NextJS and I'm not sure where exactly it's coming from. While my client side routing works fine (i.e,. Link components work as expected) it does nothing if I do this by typing in the URL. My directory structure is like this: ... - pages - _app.tsx - index.tsx - login.tsx ... Therefore I should expect /login to route to the login page and again this works as expected in the Link tag however when I manually type in localhost:8000/login/ it just redirects to index.tsx. Some other potentially relevant files: tsconfig.json { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "baseUrl": ".", "paths": { "@/styles/*": ["styles/*"], "@/components/*": ["components/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": …