Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't add new fields to UserCreationForm in Django
I want to add some fields to my forms.py like below: from django.forms import ModelForm from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CreatUserForm(UserCreationForm): first_name = forms.CharField() last_name = forms.CharField() email = forms.EmailField() class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1' ,'password2'] And also I created a register page: from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from django.forms import inlineformset_factory from urllib.parse import urlparse # from django.contrib.auth.forms import UserCreationForm from .models import * from .forms import CreatUserForm def registerPage(request): form = CreatUserForm() if request.method == 'POST': form = CreatUserForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'main/page-register.html', context) So when I remove fields first_name last_name and email I can register as a user in page-register.html but when I use these fields I can't register new user. -
How to get the number of files from request.FILES.getlist('image')
and I'm trying to upload files in the app that I'm making. I have an input field (ImageField) that accepts multiple images to be uploaded once submitted. I do this via ajax, and so I want to return some sort of json object that has total count of images being tried to upload and number of images being actually uploaded. def post_update(request): save_status = {'update_save': False, 'image_count': 0, 'image_save': 0} if request.method == 'POST': update = UpdateForm(request.POST) if update.is_valid(): event = Event.objects.get(pk=request.POST['event_id']) update_form = update.save(False) update_form.update_by = request.user update_form.event = event update_form.save() save_status['update_save'] = True images = ImageForm(request.POST, request.FILES) files = request.FILES.getlist('image_path') save_status['image_count'] = request.FILES.count if images.is_valid(): for f in files: photo = Image( image_path=f, update_ref=update_form, image_title=images.cleaned_data.get('image_title')) photo.save() save_status['image_save'] += 1 I tried request.FILES.count and request.FILES.length in trying to get the count, but to no avail and keeps having an error. My question is basically how can i get the number of files in the request.FILES? -
Using a list of objects in Django Template
This is my first time to ask a question on here so apologies if it isn't structured very well. Basically what I have is a Model called Product, which at the minute has 7 products. I am looking to pull out 3 random products from this Model and store them in a list, which I then want to access from a template to show the 3 objects which are now in the list. My attempt at getting 3 random objects from the db: ## Finding 3 random products to show all_product_list = list(Product.objects.values_list('name', 'price', 'image')) checkout_products = list() counter = 3 num_products = len(all_product_list) while counter!= 0: random_prod = random.randint(0, num_products - 1) checkout_products.append(all_product_list[random_prod]) counter -= 1 Then in my template I am trying to access as follows: {% for checkout_prod in checkout_products %} <div class="col text-light"> {{ checkout_prod.price }} </div> {% endfor %} I am also rendering the list at the end of my function as follows : return render(request, 'cart.html', {'cart_items':cart_items, 'total':total, 'counter':counter, 'data_key': data_key, 'stripe_total':stripe_total, 'description':description, 'before_discount':before_discount, 'difference': difference, 'checkout_products': checkout_products,}) I am not getting any error, but there is nothing at all showing on the page, any help with this would be greatly appreciated. Thank You! -
django authenticate not working with user created by api , only work with user created by admin
i'm trying to generated token after login using drf. i'm using emailbackend for login with email and password but its not working with user created by api and with user created by admin its working backends.py: class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None Token serializers: class AuthCustomTokenSerializer(serializers.Serializer): ''' Changing Token auth to use email instead username ''' email = serializers.EmailField(label=_("Email")) password = serializers.CharField( label=_("Password",), style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') print(email, password) if email and password: user = authenticate(username=email, password=password) print("this is user", user) # The authenticate call simply returns None for is_active=False # users. (Assuming the default ModelBackend authentication # backend.) if not user: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') else: msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs login view: @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): serializer = AuthCustomTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, _ = Token.objects.get_or_create(user=user) return Response({token: token.key}, status=status.HTTP_200_OK) -
Python, Django: list from .select_related("...")
Good day to everyone, I wonder, if there's a direct way to convert a query like this... query_db = Example.objects.all() selected_db = Example.select_related("...") print(type(selected_db)) ... <class 'django.db.models.query.QuerySet'> ...into a list? I know there are ways to do it afterwards, but are there functions like for example... ...values_list("...", flat=True) ...to solve this directly in the query? Thanks for all your help! -
django-datatable-view==0.9.0 Django 3.1.3: ImportError: cannot import name 'get_datatable_structure'
I am using the latest package django-datatable-view 0.9.0 in django 3.1.3 (upgrading from django 1.8.6) When a I run manage.py run server I get the following error: File "/mcvitty/mcvitty/customers/views.py", line 14, in <module> from datatableview.utils import get_datatable_structure ImportError: cannot import name 'get_datatable_structure' Upgrading the package is not an option as I am already using the latest package. I have searched datatableview get_datatable_structure but I cannot find it. What can I do to fix the error? Thank you for your help -
Django: send SESSION value to an extendable html template
One the one hand i have an navbar.html template that can be extended by several other html templates. On the other hand in my views i have a login system and when a user logs in im creating a session value with user's name. i want to send this session value to the navbar html but without rendering this template. How could i do this? login in view.py name = form.cleaned_data.get('name') password = form.cleaned_data.get('password') user = Users.objects.filter(name=name, password=password) if user.count() > 0: request.session['user'] = user.name return redirect("store/") else: messages.info(request, 'Invalid credentials') return redirect("/login/") the return redirect("store/")redirects to the store.html that extends the navbar.html. I want to send request.session['user'] to the navbar.html -
Django form.is_valid returns false when a FileField is set to required
So I'm trying to make a form in Django with a FileField. My forms.py looks like this: I want the FileField to be a required field. When forms.FileField(required = True) in forms.py, form.is_valid() returns false: When forms.FileField(required=False) in forms.py, form.is_valid() returns true: When I submit the form with forms.FileField(required = True) my print(form.errors) states: "This field is required" even though I do add a file. I tried different file formats to make sure the problem didn't just occur with the image I was using for testing. What am I missing? -
Dynamic Email Backend in Django
I would like to let my users decide their email backend on their own. That is why I have created the email relevant keys (host, port, username...) and now I try to work this backend into my Django project. My first attempt was to extend the default EmailBackend by my custom "UserBackend" which overrides the __init__ function like this: class UserBackend(EmailBackend): def __init__(self, user_id, host=None, port=None, username=None ...): user = User.objects.get(id=user_id) super().init(host=user.email_host, port=user.email_port ...) As this method is called (I tried to send_mail from the shell) it gets no user_id. How can I approach this differently or how would I extend my attempts to do this. I don't think it is good to essentially rewrite Djangos send_mail function (...) , as they are there and generic enough to fit my needs. -
Can't save tags in django
i am using django-taggit to save tags. It save some tags but now its not working and idk why! still finding the solution. Please help me to find out what i am doing wrong. I am not getting any errors. But when i save the form using form.save_m2m() nothing is saved in my database. I have also checked my admin pannel. Nothing is storing in my db. Is there is any way to check this. I am also attaching the template. views.py from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . models import UserCreatedNote from django.template.defaultfilters import slugify from . forms import AddNoteForm from taggit.models import Tag # Create your views here. @login_required def notes(request): if request.method=='POST': form = AddNoteForm(request.POST) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user key = form_data.note_title form_data.slug = unique_slug_generator(slugify(key)) form_data.save() #to save tags form.save_m2m() notes = UserCreatedNote.objects.filter(user=request.user) form = AddNoteForm() context = {'notes': notes,'add_note_form':form} return render(request,'usernotes.html',context) notes = UserCreatedNote.objects.filter(user=request.user) form = AddNoteForm() context = {'notes': notes,'add_note_form':form} return render(request,'usernotes.html',context) @login_required def edit(request,slug): note = get_object_or_404(UserCreatedNote, slug=slug) tagsList = [] for tag in note.note_tags.all(): tagsList.append(tag.name) print(tagsList) if request.method == 'POST': form = AddNoteForm(request.POST, instance=note) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user … -
ERROR: Your WSGIPath refers to a file that does not exist
I'm having trouble in deploying my django-react app. This is my directory tree. . ├── .elasticbeanstalk └── backend ├── .ebextensions ├── auth │ ├── management │ │ └── commands │ └── migrations ├── client │ └── build │ └── static │ ├── css │ ├── js │ └── media ├── config │ └── settings ├── postings │ ├── management │ │ └── commands │ └── migrations └── uploads # /.ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config/wsgi.py NumProcesses: 3 NumThreads: 20 # /backend/config/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.deploy") application = get_wsgi_application() And application enviroment on aws website, WSGIPath: config/wsgi.py, NumProcesses: 3, NumThreads: 20 I can't find what should I fix. -
Overrinding a field in different table on django
I want when i save new order, to save the order.id_order on company.last_order class Company(models.Model): name = models.CharField(max_length=240) last_order = models.DecimalField(max_digits=20, decimal_places=0) class Order(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) id_order = models.DecimalField(max_digits=20, decimal_places=0) -
Can i have multiple views and serializers for single model in django rest framework
I am building an application in which an owner is posting a job post and multiple user will apply for that job application. I have provided an endpoint to user to apply for a certain job post and it went successful. Then, I tried to provide a separate endpoint to an owner in which I want to view the application and edit the status of the application. To implement this I used a separate serializer which allows only status field to be updated and making rest of the fields as read only. Additionally, I created the separate view as well for the owner to update the status of the application based on id filter. Lastly, creating a separate URL as well. So, the 2 URLs are: /api/job/application (for user) /api/job/application-status (for owner) But I ended up in a situation where I am getting the same URL for both of the job application endpoint and job application status endpoint because they are using same model. So, is it possible to have multiple views and serializers for a single model? If Yes, then how can I achieve this and what permissions should I use for owner. -
Spotify authentication using Spotipy not showing and my redirect uri is refusing to connect?
Using Spotipy(A spotify module to access data using the Spotify API) and Django, I am trying to use the Authorization Code Flow for authentication but I keep running into an error when I use the login route. The URL http://localhost/?code=AQDaVeJPteLHVgQG7P41mX5XMmoriJtbpx7vjRYdTXBR64Fal2IMHXQfnSoEdrYrZnYwM-xjyyr_ME_t_gsbqR6-72A4sRBQZ1aaoJd7Xcr2rqT_9aF_kDND0XmZZMhRQzN4oAujH6Uawl9d-tEJmnE_Q-yISGAGTuIHlONwbPEretR9XdPXQg with an error localhost refused to connect comes up after I use the login route urls.py urlpatterns = [ path("login/" , views.login , name = "login" ), path("home/", views.home, name= "home"), path("callback/" , views.callback , name="callback") ] views.py #get_authorize_url()method returns a Spotify API endpoint https://accounts.spotify.com/authorize?client_id=83654ff787fc48c7a38cc7976238628a&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2F&scope=user-library-read def login(request): authorize_url = oauth.get_authorize_url() return redirect(authorize_url) get_access_token() returns the access token def callback(request): code = request.GET.get("code") if code is not None: oauth.get_access_token(code) return redirect(reverse("home")) else: return redirect(reverse("login")) def home(request): return HttpResponse("Welcome") -
How to change the beginning id in django?
I'm trying to set an AutoField starting point to 1000, instead of 1, 2, 3, ... I want to make it 1001, 1002, 1003, ... here's the model: class User(models.Model): id = models.AutoField(min_length=4) getting this error after running makemigrations command. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Python38\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\test\Desktop\mhlogo\users\models.py", line 5, in <module> class User(models.Model): File "C:\Users\test\Desktop\mhlogo\users\models.py", line 6, in User id = models.AutoField(min_length=4) File "C:\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2357, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'min_length' using django 3.1 and mariadb 10.4 -
Django, MVC pitfalls for POSTs when rev proxy down, caching failed POSTs, none user Auth
Disclaimer Firstly, I understand SO is for code based answers, I did some research on where to ask this questions, and it seems like according to the community SO got 20 votes for asking: Questions about deployment and support of applications past release, in particular towards design for maintainability. Intro My question is I personally spent last 2 years working on a Django project for a factory, it uses the standard MVC pattern. The app uses the factory IP for authentication for terminals in the factory. It was my first web project and I have learnt a lot from it, and hence re-written many aspects of it. 3 Problems with Django MVC However I have now reached a point where I am wondering if it needs a re-write since I see no great solutions to the following problems with the MVC pattern: I wish to be able to POST data, and control what happens if it fails on the client side. With a normal POST, once one has submitted the form, one let's go of control. This means if the server is restarting, or receiving an update, and the reverse proxy (UWSGI) is not up yet, Nginx shows an error … -
Error while trying to pip install mysqlclient in my django project?
ERROR: Command errored out with exit status 1: ... cwd: /tmp/pip-install-0w18_khs/mysqlclient/ Complete output (12 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-0w18_khs/mysqlclient/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-0w18_khs/mysqlclient/setup_posix.py", line 65, in get_config libs = mysql_config("libs") File "/tmp/pip-install-0w18_khs/mysqlclient/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django. How do I add a field to a query result?
I have a Room model and I want to add the is_member boolean field to a queryset with rooms. How can do this? I was thinking of using .annotate (), but that doesn't work for my task. models.py from django.db import models class Room(models.Model): name = models.CharField(max_length=150) members = models.ManyToManyField(User, blank=True) views.py from rest_framework.views import APIView from rest_framework.response import Response from .serializers import RoomSerializer from .models import Room class RoomView(APIView): def get(self, request): rooms = Room.objects.all() # get all rooms user = request.user # get current user for room in rooms: members = room.members.all() # get members is_member = user in members # set boolean value room.is_member = is_member # set in room serializer = RoomSerializer(rooms, many=True) return Response(serializer.data) serializers.py from rest_framework import serializers from .models import Room class RoomSerializer(serializers.ModelSerializer) is_member = serializers.BooleanField(read_only=True) class Meta: model = Room fields = "__all__" I solved this issue this way, but is there any other options to do it? Help me please -
Django | REST | Three related tables to JSON
please I need advice - is possible to reach a JSON output like this: data: code: A, get_code_display: ATV makes: Honda: model_set: Rancher SXS500 M code: T, get_code_display: Automobile makes: BMW: model_set: X6 535i Audi: model_set: A8 A6 A4 code: M, get_code_display: Motorcycle makes: Honda: model_set: CB1000R CB500F Yamaha: model_set: R1 R6 With model of database, like this: models.py: TYPE_CHOICES = ( ('A', 'ATV'), ('T', 'Automobile'), ('M', 'Motorcycle'), ) class Make(models.Model): name = models.CharField(max_length=64) class Type(models.Model): code = models.CharField(max_length=1, choices=TYPE_CHOICES, unique=True) class Model(models.Model): make = models.ForeignKey(Make, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) name = models.CharField(max_length=64) class Vehicle(models.Model): make = models.ForeignKey(Make, on_delete=models.CASCADE) model = models.ForeignKey(Model, on_delete=models.CASCADE) name = models.CharField(max_length=64) With Django Rest Framework? What I am able to do, is get model_set from a Make and Type, but is there any way, how to combine these? Or this DB model is bad? I have added ForeignKey of Type to Model table, because for example Honda can produce Automobiles and also Motorcycles - just name of its vehicle model will be different. Another option here, is to use two serializers - for Make and Type with Filtering in Rest framework via django-filter, but when I created solution, which should work, I am able … -
Django application mod_wsgi error with apache
I'm hosting Django app on AWS ec2 with ubuntu 20.04 lts. I can run the app with venv on various ports. I want to bind the app with apache so that my users can visit my app with just the public DNS no ports, only on the default port. So I have installed apache2, mod_wsgi. My virtual host configuration. <VirtualHost *:80> ServerAdmin test@example.com DocumentRoot /var/www/html/app_folder ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/html/app_folder/static <Directory /var/www/html/app_folder/static> Require all granted </Directory> Alias /static /var/www/html/app_folder/media <Directory /var/www/html/app_folder/media> Require all granted </Directory> <Directory /var/www/html/app_folder/main_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess app_folder python-path=/var/www/html/app_folder python-home=/home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py WSGIProcessGroup app_folder WSGIScriptAlias / /var/www/html/app_folder/main_app/wsgi.py </VirtualHost> So after configuring this vhost i restart my apache2 but I get nothing on the public dns. Instead I get the following error logs on my /var/log/apache2/error.log [Wed Dec 02 08:50:05.967958 2020] [wsgi:warn] [pid 121300] (13)Permission denied: mod_wsgi (pid=121300): Unable to stat Python home /home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site … -
Bootstrap popover does not work with downloaded js and css
I am having some weird problem with using popover in my django app. When using the css and js of a latest version of bootstrap it simply does not work. When I use link to 3.4.1 version I found in some tutorial everything works just fine. I'm attaching code that doesn't work and the one that does. Did popover function got removed in latest bootstrap? Works (3.5.1): <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <a href="#" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Toggle popover</a> <script> $(document).ready(function(){ $('[data-toggle="popover"]').popover(); }); </script> Does not work (4.5.x): <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <a href="#" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Toggle popover</a> <script> $(document).ready(function(){ $('[data-toggle="popover"]').popover(); }); </script> -
how to add category to blog project django
i developed a blog project by watching many open-source courses and create my own django custom admin dashboard where i want to add a category option to my blog project, i have watched some tutorial on as well but couldn't find them helpful models.py from django.db import models from django.forms import ModelForm from farmingwave.models import BaseHeader,Submenu class Category(models.Model): mainmenu=models.ForeignKey(BaseHeader,null=True,on_delete=models.SET_NULL) submenu=models.ForeignKey(Submenu,on_delete=models.CASCADE) class AdSideMenu(models.Model): title_id = models.AutoField(primary_key=True) title_name = models.TextField() url = models.TextField() priority = models.IntegerField() submenu_status = models.TextField() class Meta: db_table = 'admin_side' class CreateBlog(models.Model): id = models.AutoField(primary_key=True) blog_Title = models.TextField(max_length=100) content = models.TextField(max_length=5000) category = models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) class Meta: db_table = 'create_blog' they are inhereting data from another app models.py `class BaseHeader(models.Model): main_id = models.AutoField(primary_key=True) title_name = models.TextField() url = models.TextField() priority = models.IntegerField() submenu_status = models.TextField("false") class Meta: db_table = 'base_header' class Submenu(models.Model): sub_id = models.AutoField(primary_key=True) main_id = models.IntegerField() sub_name = models.TextField() url = models.TextField() priority = models.IntegerField() mainmenu=models.ForeignKey(BaseHeader,on_delete=models.CASCADE) class meta: db_table = 'base_subheader'` and the view function: def create_blog(request): if request.method =='POST': form = CreateBlogForm(request.POST) if form.is_valid(): form.save() form = CreateBlogForm() else: form = CreateBlogForm() base = BaseHeader.objects.all() sub = Submenu.objects.all() create = CreateBlog.objects.all() category = Category.objects.all() context = { 'form' : form, 'createblog' : create, 'category' : category, … -
Translating code from Django version 1.9 to version 2.0
I am currently trying to get started with Django. But the book am using is using Django version <1.9 while the current version is >2.0 The problem am facing right now is this code: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('learning_logs.urls', namespace = learning_logs')) ] I have looked around and this is what I have written from django.contrib import admin from django.urls import include, path app_name = 'learning_logs' urlpatterns = [ path('admin/', admin.site.urls), path('learning_logs/', include('learning_logs.urls', namespace = 'learning_logs')), ] but when I run the server I get the error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Any help with this. Thanks in advance -
Reverse for 'staff_info_update' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/staff/info/edit/(?P<pk>[0-9]+)/$']
I want to update additional information of staff class from update view of user class, where staff class has one to one relation with user class. These are my codes models class StaffInfo(models.Model): user = models.OneToOneField(User, related_name='staff_information', on_delete=models.CASCADE) views class StaffUpdateView(UpdateView): model = User form_class = StaffEditForm template_name = 'forms/staff_edit_form.html' context_object_name = 'staff' templates <a href="{% url 'staff_info_update' staff.staff_information.pk %}"> Additional Information </a> url path('admin/staff/info/edit/<int:pk>/', StaffAddInfoUpdateView.as_view(), name='staff_info_update'), -
How to use Django and angular together?
I've a django backend and angular frontend, on my local machine to use both together, I've to run both server's using ng serve and python manage.py runserver but now I'm planning to deploy it to heroku and I've no idea how will it work, also is there any official guide for using django and angular together. P.S. - I'm using django-rest-framework for making api calls from frontend to backend.