Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django with celery raise No module named 'kombu' when runserver
I made a website with django and I use celery for asynchronous task, when I run: ./manage.py runserver I got the error: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/db/utils.py", line 225, in close_all for alias in self: File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/db/utils.py", line 219, in __iter__ return iter(self.databases) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/rouizi/OC_project13/car_rental/__init__.py", … -
How to import .uff pipe delimited text file to Django database?
I have a .uff file that contains multiple lines of pipe-delimited text. I have created a Django model and would like to extract relevant information from the text file and import it to my SQLite database. How can I access the information from a .uff file? -
Prop being mutated (in django templates and Vue.js with CDN)
I have a small django project and frontend is coded with Vue.js via CDN. So it has only one server for django. And vue is placed into django templates. DRF is the source of web apis. Django 2.2.10, DRF 3.11.0 and vue gets the latest from CDN. Vuetify (again from CDN) gives material UI design with v-app-bar, v-navigation-drawer and v-footer. Also Vuetify's v-data-table is used for two datasets. (countries and their cities) I can show the data when the page first responded. HOWEVER, when the drawer is closed with a button click or when the 'rows per page' of v-data-table has changed, data disappears. I should refresh the page to get it back. error is: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "tableData" found in ---> <LocCountry> <VContent> <VApp> <Root> list page: {% extends 'locations/index.html' %} {% load static%} {% block content %} <loc-country></loc-country> {% endblock %}{% block extrascript %} <script> Vue.component("loc-country", { props: ["tableData"], template: ` <v-data-table :headers="headers" :items="tableData" class="elevation-1"></v-data-table> `, data() { return { // tableData: null, loading: true, errored: false, headers: … -
Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update_order\\/(?P<pk>[^/]+)\\/$']
I guess there is some error in updateorder function, but I cannot find it. When I am clicking on the update button in dashboard.html it gives an error saying that Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update_order\/(?P[^/]+)\/$'] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from accounts.models import * from accounts.forms import OrderForm # Create your views here. def home(request): customers = Customer.objects.all() orders = Order.objects.all() total_customers = customers.count() total_orders = orders.count() pending = orders.filter(status='Pending').count() delivered = orders.filter(status='Delivered').count() context = {'customers':customers, 'orders':orders, 'pending':pending, 'delivered':delivered, 'total_customers':total_customers, 'total_orders':total_orders} return render(request, 'accounts/dashboard.html', context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html', {'products':products}) def customer(request, pk): customers = Customer.objects.get(id=pk) orders = Order.objects.all() orders_counts = orders.count() context = {'customers':customers, 'orders':orders, 'orders_counts':orders_counts} return render(request, 'accounts/customer.html', context) def createorder(request): form = OrderForm if request.method=='POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'accounts/order_form.html', context) def updateorder(request, pk): orders = Order.objects.get(id = pk) form = OrderForm(instance = orders) context = {'form':form} return render(request, 'accounts/order_form.html', context) > Blockquote urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home'), path('products/', views.products, name = 'products'), path('customer/<str:pk>/', views.customer, name = 'customer'), path('create_order/', views.createorder, … -
How to configure IPN paypal for live transaction in django
It works for sandbox but it's not works for live transaction. I don't have idea how to configure for live transaction. Please help me I am searching solution for this problem from last 3 days. def process_payment(request): domain=request.session.get('domain_name') key = request.session.get('key') keystore=request.session.get('keystore') flag=request.session.get('flag') emails=str(request.user) strings= key+" "+emails+" "+keystore+" "+str(flag) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '19.00', 'item_name': 'Order', 'invoice': domain, 'currency_code': 'USD', 'custom':strings, 'notify_url': 'http://{}{}'.format(host,reverse('paypal-ipn')), 'return_url': 'http://{}{}'.format(host, reverse('payment_done')), 'cancel_return': 'http://{}{}'.format(host,reverse('payment_cancelled')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/process.html', {'form':form}) -
In Django, how to know which button was pressed?
Here is my html, I have two buttons, one for accepting and the other for rejecting the request. In my view, I need to know which button was pressed along with the email of the applicant (tutor_application.tutor.chalkslateuser.email). I tried many solutions but to no avail. {% for tutor_application in tutor_application_list %} <div class="card" style="width: 15rem;"> <img src="{{ tutor_application.tutor.picture.url }}" class="card-img-top" > <div class="card-body"> <h5 class="card-title"> {{ tutor_application.tutor.chalkslate_user.first_name }} {{ tutor_application.tutor.chalkslate_user.last_name }} </h5> <h6 class="card-subtitle mb-2 text-muted">{{ tutor_application.note }}</h6> <h6 class="card-subtitle mb-2 text-muted">{{ tutor_application.posted }}</h6> </div> <a class="btn btn-outline-success" role="button" type="submit"> Accept </a> <a class="btn btn-outline-danger" href="#" role="button"> Reject </a> </div> {% endfor %} -
format output not working anymore in new version of django
def render(self, name, value, attrs=None, renderer=None): if not value: value = [ x for x in self.widgets] rendered_widgets = [ x.render('%s_%d' % (name,i), value[i]) for i,x in enumerate(self.widgets) ] context = {'fields': rendered_widgets} return render_to_string('tifact/widgets/newdevicewidget.html', context) I am migrating from django 1.8 to django 2.2 , and MY below code i am trying to mgirate it above. THe issue I have, the textinput are coming filled with data. I dont want to touch them. JUst display as they were created.SOmeone help. def format_output(self, rendered_widgets): # formats the fields to be displayed horizontally context = {'fields': rendered_widgets} return render_to_string('tifact/widgets/newdevicewidget.html', context) -
How to add two url's together in de {% static %} tag in django
Does somebody know if it is possible to add following two strings together, so that django reads it as one url. Django: src="{% static 'post_it/media/post_images/' + '{{ post.image_name }}' %}" Thanks -
Django subquery outerref('id') You might need to add explicit type casts
I'm using postgresql. i write subquery in subquery i want to apply filter on id of parent table with field of child table. but it shows error query: orders = Order.objects.filter(user=request.user, status='P') albums = models.Album.objects.annotate(purchased_status=Subquery(orders.values('id').filter(item_id=OuterRef('id'))[:1])) Error django.db.utils.ProgrammingError: operator does not exist: character varying = integer LINE 1: ...atus" = 'P' AND U0."user_id" = 1 AND U0."item_id" = "bookcen... HINT: No operator matches the given name and argument types. You might need to add explicit type casts. if i apply filter on any of field other then id it work fine. this error fix if i will add id for parent table as foreign key in child table but don't want to do this. issue if because OuterRef('id') return reference id not just integer value like 1 or 2 is there any way with which OuterRef('id') can return integer value of id. -
Django admin change_view does not pass extra_context to html
I'm looking for quite some time now to get extra_context passed to the html of the admin change view. The rendered change form only shows the H tags. I've checked my data up till it gets returned and all seems ok. It just will not be passed forward. Strangely I don't get any errors on indexing in html page. Does somebody spot a mistake? admin.py class CustomerAdmin(admin.ModelAdmin): list_display = ("name", "company", "country", "invoice_currency") search_fields = ["name", "company", "country"] list_filter = (TotalInvoiceOver1kFilter,) actions = [get_all_customers_invoices,] change_form_template = 'admin/crm/change_form.html' def change_view(self, request, object_id, form_url='', extra_context=None): extra = extra_context or {} extra['last_three_inv'] = Invoice.objects \ .filter(inv_customer=object_id) \ .order_by('-inv_date')[0:3] extra['total_amount_12_months'] = Invoice.objects \ .filter(inv_customer=object_id) \ .aggregate(Sum('inv_amount')) return super(CustomerAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) change_form.html <!DOCTYPE html> {% extends "admin/change_form.html" %} {% block form_top %} <h2>Last 3 invoices:</h2> {% for invoice in extra_context.last_three_inv %} {{invoice.inv_number}} {% endfor %} <h2>Total amount past 12 months:</h2> {{extra_context.total_amount_12_months.inv_amount__sum}} {% endblock %} -
default context for all pages Django
I was wondering if there's any way of sending a default context for all pages in django, such as user is always passed to the template regardless of other context, for my particular case i want to send context for navbar such as category and sub category to all pages without having to send in all the views. TIA -
How to read contents of zip file in memory on a file upload in python?
I have a zip file that I receive when the user uploads a file. The zip essentially contains a json file which I want to read and process without having to create the zip file first, then unzipping it and then reading the content of the inner file. Currently I only the longer process which is something like below import json import zipfile @csrf_exempt def get_zip(request): try: if request.method == "POST": try: client_file = request.FILES['file'] file_path = "/some/path/" # first dump the zip file to a directory with open(file_path + '%s' % client_file.name, 'wb+') as dest: for chunk in client_file.chunks(): dest.write(chunk) # unzip the zip file to the same directory with zipfile.ZipFile(file_path + client_file.name, 'r') as zip_ref: zip_ref.extractall(file_path) # at this point we get a json file from the zip say `test.json` # read the json file content with open(file_path + "test.json", "r") as fo: json_content = json.load(fo) doSomething(json_content) return HttpResponse(0) except Exception as e: return HttpResponse(1) As you can see, this involves 3 steps to finally get the content from the zip file into memory. What I want is get the content of the zip file and load directly into memory. I did find some similar questions in stack … -
Custom Django User Model Setup from Existing (Drupal) Database Table
I’m working on a project to replace a Drupal 6 application, and am trying to figure out how to use its MySQL ‘users’ table to create my Django user models for authentication. Both apps are housed on the same server so I have easy access to the db. The Drupal ‘users’ database is still actively used for a greater application from which my project is a subset, so I am not able to restructure it, and I’m hoping to avoid requiring separate accounts for my app since it is all part of the same ecosystem/has existing users. I can't just copy the existing users to a new table as people will continue to make accounts on the Drupal system. I’ve researched AbstractUser and AbstractBaseUser, but have not found a way to assign columns from an existing table to the username and password variables. All of the custom user model solutions seem to assume that the user database is starting fresh, and takes care of assigning, storing, and saving usernames and passwords behind the scenes. I’m considering using a standard User model, checking unrecognized usernames and passwords against the Drupal User db, and creating a new Django user on the first … -
Debug a background django request (show local variables)
Here's my setting: 2 Django services (A and B) run in production using gunicorn+nginx. The user logs into service A and adds an object entry then clicks submit which generates an XHR request (1) Service A recieves the request (1) and publishes in background the new object to service B. (request 2 When B recieves and handles the request (2), the error occurs. Both the services have DEBUG = True and logging level set to 'DEBUG'. To debug the error, I need to access values of local variables in the error's stack trace. I can't in the browser because I am far from the faulty service (XHR then a background process request to a remote service). The console prints stack trace but without local variables. Is there a simple way to achieve the result I want ? Regards -
how to implement user manager to create custom user using AbstractUser class?
im trying to make my own custom user model with AbstractUser class class CustomUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) def __str__(self): return self.username class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) def __str__(self): return self.user.username but when i create new account the password field wont been encrypted it show only a plain text ! i think i should use BaseUserManager but i dont have any idea to make it thanks , regards .. -
Getting a query set between a range of dates Django
I'm trying to return a list of items in between 2 different dates, a date in the past and the current time using a queryset. The error I'm getting is TypeError: an integer is required (got type str) views.py import datetime import pytz first_date = "2020-01-01 19:17:35.909424" last_date = timezone.now() I don't want anything returned that has a date in the future Here is the filter in the query .filter(hide_sentance_until=(date(first_date), date(last_date))) This is the full queryset, but it's the above filter causing he issue zip_flash_sentances = model.objects.filter(show_sentance=True).filter(hide_sentance_until=(date(first_date), date(last_date))).order_by("?").filter(username_id = user_id_fk).values_list('sentance_eng', 'sentance_esp', 'id').first() I thought it might be a comparison problem with dates but here is my model field models.py hide_sentance_until = models.DateTimeField(default=datetime.now(), blank=True) Thanks -
How to Import a bootstrap template in django, static function not working ;-;
I am trying to import a bootstrap template into my django app using the static function to render all of the static elements in to the app but it does not seem to work, I have followed the tutorial on the django homepage but it still doesn't work.The name of my template is inbox.html. Here is the code for my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p2(ljol9n-6g_#=!lb!c@z_#3u#2b8*hj4=^ou7!)=7q^r^sz9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'CollectMail.apps.CollectMailConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'guardian', ] 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 = 'Emails.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], '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 = 'Emails.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, … -
'learning_logs' is not a registered namespace
I have been seeing the following error. How can I solve it? Error: 'learning_logs' is not a registered namespace urls.py """Defines URL pattern for learning_logs""" from django.conf.urls import url from . import views app_name = 'learning_log' urlpatterns = [ #Home page url(r'^$', views.index, name='index'), url(r'^topics/$', views.topics, name='topics'), ]``` #base.html '''<p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> - <a href="{% url 'learning_logs:topics' %}">Topics</a> </p> {% block content %}{%endblock content %} -
Download to client browser using youtube_dl
How can I use youtube_DL to download directly to a clients browser instead of my project file with python django -
Django not installing
I am trying to instal Django on my new mac. I am not able to do so. Please advice. I also tried sudo commmands, but this only installs with python 2 and not 3 -
Django models from other project
Currently I have a Django project for an Online Shop. It has many models like Order, Product and others. This project is relatively big and has 40+ models and more than 8 apps. Now I need to create an Admin platform for the shop. In this platform I must be able to see all the orders made by all users, all the companies which sell their products in my shop and a lot of other data. Obviously, it must use the same database the shop uses which leads me to using the same models to work with the data as the Shop project uses. This is where I have a problem. Somehow I need to get access to models from Shop project in the Admin project. I see several solutions: To create a pip package from my Shop project and import it in the Admin project. However, my shop project is still in active development and I make changes to its code very frequently, so, I will have to rebuild and reinstall it every time I make the changes. Considering this I think that this isn't the option. Use Shop's API in Admin project. By this I mean that I … -
Forbidden (CSRF token missing or incorrect.): Django form
I'm trying to subscribe an email account into a newsletter using Django, when I try to click the Go button I get the error Forbidden (CSRF token missing or incorrect.): Here is the views.py method: def newsletterSubscribe(request): try: form = NewsletterUserSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): messages.warning(request, _('Alerta! El correo ingresado ya se encuentra suscrito.'), 'alert alert-warning alert-dismissible') else: instance.save() messages.success(request, _('Correo agregado con exito!'), 'alert alert-success alert-dismissible') subject = _('Gracias por unirse a nuestro boletín') message = _("""Bienvenido al boletín de ADA Robotics. Si deseas no estar suscrito visita: https://127.0.0.1:8000/unsubscribed""") msg = MIMEMultipart('alternative') msg['From'] = settings.EMAIL_HOST_USER msg['To'] = instance.email msg['Subject'] = subject part = MIMEText(message, 'plain') msg.attach(part) mail = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT, timeout=20) mail.starttls() """ template = get_template("myapp/sample_template.html") context = Context(context_data) body_html = template.render(context_data) body_text = strip_tags(body_html) part1 = MIMEText(body_text, 'plain') part2 = MIMEText(body_html, 'html') msg.attach(part1) msg.attach(part2) """ emailto = [instance.email] mail.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) mail.sendmail(settings.EMAIL_HOST_USER, emailto, msg.as_string()) mail.quit() """from_email = settings.EMAIL_HOST_USER to_email = [instance.email] send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=message, fail_silently=False)""" context = { 'form': form, } template = 'subscribed.html' #return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return render(request, template) except Exception as ex: return render(request, '404.html') Here is the template code: <form id="newsletterForm" action="{% url "newsletterSubscribe" %}" method="POST" class="mr-4 mb-3 mb-md-0"> {% csrf_token … -
Custom calculated column in django_tables2 with one value from html form a the other from database
I am new to Django and currently trying to make a table in django_tables2 with a columns which would display a value from databes(in this case v_pole,v_les,v_celkem) and value from text input in form (cena) multiplied together. After choosing the generovat option in views.py site will take you to pozemky url where the second table with those calculations shuld be generated. [v_pole,v_les,v_celkem are actually values of acreage of field and the "cena" is price which would user set to a certain number] Any valuable information on direction to take would be welcome, thanks. #models.py class Majitele(models.Model): lv = models.IntegerField() katastr = models.CharField(max_length=40) jmeno = models.CharField(max_length=40) ulice = models.CharField(max_length=30) mesto = models.CharField(max_length=30) psc = models.IntegerField() v_pole = models.DecimalField(decimal_places=4, max_digits=10) v_les = models.DecimalField(decimal_places=4, max_digits=10) v_celkem = models.DecimalField(decimal_places=4, max_digits=10) cena_pole = models.IntegerField() cena_les = models.IntegerField() cena_rok = models.IntegerField() nevyplaceno = models.IntegerField() podil = models.CharField(max_length=5) hlasu = models.IntegerField() poznamka = models.CharField(max_length=200) prezence = models.BooleanField() vyplatni = models.BooleanField() postou = models.BooleanField() osobne = models.BooleanField() #urls.py urlpatterns = [ path('admin/', admin.site.urls), path('base/', base_view, name='base'), path('', majitele_view_post, name='tab1_post' ), path('', majitele_view_get, name='tab1_get' ), path('pozemky/', pozemky_view_post, name='tab2_post'), path('pozemky/', pozemky_view_get, name='tab2_get'), ] #views.py def majitele_view_get(request): if request.method == "GET": table = MajiteleTable(Majitele.objects.all()) return render(request, 'tabrender.html', context={'table': table}) def majitele_view_post(request): … -
Not able to post to Django REST API
I wanted to create the ViewSet which return list of objects when doing GET request, and in case POST request it will execute the function and only after this will return this list. I did this like in the documentation, but receiving that "post" is not allowed. views.py class CloudViewSetHosts(viewsets.ModelViewSet): queryset = CloudModelHost.objects.all() serializer_class = CloudSerializerHosts @action(methods=['POST'], detail=True, url_path='autodiscovery', url_name='autodiscovery') def autodiscovery(self, request, requestDataName=None): ... some actions ... return CloudModelHost.objects.all() urls.py router = routers.DefaultRouter() router.register(r'hosts', CloudViewSetHosts) urlpatterns = [ path('', include(router.urls)), ] And curl out : curl -X POST -H 'Accept: application/json; indent=4' http://IP/api/hosts/test/ -vvv * Trying IP:80... * TCP_NODELAY set * Connected to IP (IP) port 80 (#0) POST /api/hosts/test/ HTTP/1.1 Host: IP User-Agent: curl/7.65.3 Accept: application/json; indent=4 Mark bundle as not supporting multiuse < HTTP/1.1 405 Method Not Allowed < Date: Tue, 03 Mar 2020 19:20:38 GMT < Server: Apache/2.4.41 (Ubuntu) < Content-Length: 48 < Vary: Accept < Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS < X-Frame-Options: DENY < X-Content-Type-Options: nosniff < Content-Type: application/json < { "detail": "Method \"POST\" not allowed." Connection #0 to host IP left intact -
inlineformset_factory shows empty dropdown for id_modelname
when creating a formset from a fromset_factory, I get an empty dropdown menu for the model id. How to prevent django from doing this? Related code: Experience model class Experience(models.Model): hnuser = models.ForeignKey(HNuser, on_delete=models.CASCADE, blank=True, default='') activity = models.CharField(max_length=30, null=True, blank=True, default='') campaign = models.CharField(max_length=30, null=True, blank=True, default='') location = models.CharField(max_length=30, null=True, blank=True, default='') year = models.CharField(max_length=4, null=True, blank=True, default='') def __str__(self): return '' class Meta: ordering = ['-year'] verbose_name_plural = 'Experiences' Related HNuser model: class HNuser(AbstractUser): username = None # Make the email field required and unique email = models.EmailField('email address', unique=True) # Set the USERNAME_FIELD--which defines the unique identifier for the User model--to email USERNAME_FIELD = 'email' # additional required fields REQUIRED_FIELDS = [] # Specified that all objects for the class come from the CustomUserManager objects = HNuserManager() def __str__(self): return str(self.id) To be short, in view.py I did this exp_form = ExpFormSet(instance=HNuser.objects.get(pk=user_id)) return render(request,'users/edit_profile.html', { 'exp_form':exp_form, }) And in the template <table class="table"> {{exp_form}} </table> I tried to exclude the field 'id_experiences' in exp_form definition. But since it is not an Experience model attribute, this didn't work. Is anybody out there with an idea what is going on? Any hint is appreciated.