Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerfile Django not opening in browser
I'm using Django 2.x and dockerizing the application. I have the following Dockerfile content. FROM python:3.7-alpine # Install Rabbit-mq server RUN echo @testing http://nl.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories RUN apk --update add \ libxml2-dev \ libxslt-dev \ libffi-dev \ gcc \ musl-dev \ libgcc curl \ jpeg-dev \ zlib-dev \ freetype-dev \ lcms2-dev \ openjpeg-dev \ tiff-dev \ tk-dev \ tcl-dev \ mariadb-connector-c-dev \ supervisor \ nginx \ --no-cache bash # Set environment variable ENV PYTHONUNBUFFERED 1 # Set locale variables ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 # -- Install Application into container: RUN set -ex && mkdir /app # -- Adding dependencies: ADD . /app/ # Copy environment variable file ADD src/production.env /app/src/.env COPY scripts/docker/entrypoint.sh /app/ # Switch to the working directory WORKDIR /app RUN chmod ug+x /app/entrypoint.sh # Install Pipenv first to use pipenv module RUN pip install pipenv # -- Adding Pipfiles ONBUILD COPY Pipfile Pipfile ONBUILD COPY Pipfile.lock Pipfile.lock RUN pipenv install --system --deploy RUN mkdir -p /etc/supervisor.d COPY configs/docker/supervisor/supervisor.conf /etc/supervisor.d/supervisord.ini EXPOSE 80 8000 CMD ["/app/entrypoint.sh"] and the entrypoint.sh hash #!/usr/bin/env bash exec gunicorn --pythonpath src qcg.wsgi:application -w 3 -b 0.0.0.0:8000 -t 300 --max-requests=100 I use the command to build the image docker build . -t qcg_new and … -
How to literally get the `get_change_message` in `django.contrib.admin.models.LogEntry` in django 2.2
I've added a code in my view to log every add action in my add_new_staff page. Here's the code: message = f'New user added. Added staff profile for {user.first_name} {user.last_name}' log = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(user).pk, object_id=repr(user.id), # or any field you wish to represent here object_repr=repr(user.username), action_flag=ADDITION, # assuming it's a new object change_message=message,) # a new user has been added log.save() In here, I only made a custom get message thru message string. And I think, for this add_staff_view it is ok to do this. But now, I'm working on my update_staff_profile_view and also, I need to log this action. I saw how the change/update form in django admin page inserts the change_message in LogEntry model and I can't think of ways to do it inside my own update_staff_profile_view. Any help would be really appreciated, thank you! -
Having a pull request conflict issue
I am trying to merge a branch with the master branch but my conflict is hard to resolve as it says use cmd line and with the cmd line options give it doesnt resolve the issue. Github is giving me this... Step 1: From your project repository, bring in the changes and test. git fetch origin git checkout -b static origin/static git merge master Step 2: Merge the changes and update on GitHub. git checkout master git merge --no-ff static git push origin master Then when i try it i get this output (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git fetch origin (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git checkout -b static origin/static fatal: A branch named 'static' already exists. (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git merge master Already up to date. (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git checkout master Switched to branch 'master' Your branch and 'origin/master' have diverged, and have 2 and 2 different commits each, respectively. (use "git pull" to merge the remote branch into yours) (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git merge --no-ff static Already up to date. (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git push origin master To fortress-sefa.git ! [rejected] master -> master (non-fast-forward) The conflicting files are DEMOPROJECT/__pycache__/__init__.cpython-37.pyc DEMOPROJECT/__pycache__/settings.cpython-37.pyc DEMOPROJECT/__pycache__/urls.cpython-37.pyc DEMOPROJECT/__pycache__/wsgi.cpython-37.pyc Is there a significance in the fact it is cache files? -
How do you render form from views in template without model?
I have a problem with my Django Code.I'm trying to render a form from views to template and it is not working. I noticed that we can use forms dynamically by introducing it like this {{ form }}, but it's not working. I join my four files: views.py, home.html, forms.py and urls.py Thank you in advance **home.html** {% csrf_token %} <fieldset> <legend class="border-bottom mb-4">Home</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> **views.py** def inputHome(request): form = InputHomeForm() if request.method == 'POST': form = InputHomeForm(request.POST) if form.is_valid(): mk = form.cleaned_data['mk'] return HttpResponseRedirect('blog-config') else: form = InputHomeForm() return render(request, 'blog/home.html', {'form': form}) **forms.py** class InputHomeForm(forms.Form): mk = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'})) **urls.py** urlpatterns = [ path('home/', blog_views.home, name='blog-home'), ] I don't have an error message so i don't have an idea of the problem -
how to upload large files in django temp directory location?
def handle_uploaded_file(f): with open('/home/arvind/Desktop/newupload/documents/'+f.name, 'wb') as destination: filepath = destination.name for chunk in f.chunks(): #time.sleep(1) destination.write(chunk) # def fileupload(request): if request.method == 'POST': files = request.FILES.getlist('uploadfile') for f in files: handle_uploaded_file(f) return HttpResponse('add') return HttpResponse("done") -
Getting Error in middleware for the mobileesp While porting python2 project to python3
I'm getting the error in the dependencies while porting python2 project with Django 1.1.11 to python 3.7 and Django 2.2.5 I'm using Django-mobileesp in the python2, when I have update the code to python3 it gives the error for the Middleware for the UserAgent. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/home/jarvis/Desktop/law3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/jarvis/Desktop/law3/src/lawersify/wsgi.py", line 5, in <module> application = get_wsgi_application() File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 135, in __init__ self.load_middleware() File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/handlers/base.py", line … -
Django admin inline - show only when changing object
I have a UserProfile which has many required fields and I'm trying not to show it when adding user. I tried multiple things, for example: def get_formsets_with_inlines(self, request, obj=None): if not obj: return [] return super().get_formsets_with_inlines(request, obj) But after saving User, django raises error which says that fields from UserProfile can't be null. Do you know how to make it work? -
Djnago - getting two entries in the database, one with null and other with all data captured
I have a form and am updating the database with the form entries. I see that there are two rows getting updated one with NULL entries and other with all data. There is something wrong in my view but I don't know what, please help. models.py class Metadataform(models.Model): Models = models.CharField(max_length=5000, blank=True) Device = models.CharField(max_length=500, blank=True) Document = models.FileField(upload_to='') views.py def submission(request): Models = request.POST["Models"] Device = request.POST["Device"] Error_Estimation = request.POST["Error_Estimation"] if request.method == 'POST': form = Fileuploadform(request.POST, request.FILES) if form.is_valid(): form.save() newdoc = Metadataform(Document = request.FILES['Document']) newdoc.save() return render(request, "home.html") else: form = Fileuploadform() There are two-row entries in the database. 1 row with NULL entries and the uploaded file link, another row with all the data and the file link -
Change Session Table Name and Customize Django Session Table
My problem: I'm trying to change the Django session table name from "django_session" to some other name as "User_session" What I tried: from django.contrib.sessions.models import Session Session._meta.db_table = "my_session" I placed the above code in Project's __init__.py file. But I'm getting error as calling session before the Session middleware has been initialized. What I want: I need to change the django_session table name to some other table name and add few columns to that table. NOTE: I'm using Django 2.1.11 and Python 3.7 Kindly help me to get rid off this problem. -
gunicorn not starting (code=exited, status=1/FAILURE) error
not able to start gunicorn in my server sock file is not creating in my project directry Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2019-09-16 09:35:37 UTC; 2s ago Main PID: 22932 (code=exited, status=1/FAILURE) Sep 16 09:35:31 django gunicorn[22932]: [2019-09-16 09:35:31 +0000] [22932] [INFO] Starting gunicorn 19.9.0 Sep 16 09:35:31 django gunicorn[22932]: [2019-09-16 09:35:31 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:32 django gunicorn[22932]: [2019-09-16 09:35:32 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:33 django gunicorn[22932]: [2019-09-16 09:35:33 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:34 django gunicorn[22932]: [2019-09-16 09:35:34 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:35 django gunicorn[22932]: [2019-09-16 09:35:35 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:36 django gunicorn[22932]: [2019-09-16 09:35:36 +0000] [22932] [ERROR] Can't connect to Sep 16 09:35:37 django systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Sep 16 09:35:37 django systemd[1]: gunicorn.service: Unit entered failed state. Sep 16 09:35:37 django systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
I am trying to install django in my windows system with the command "conda install django" , anaconda python3 is already installed and working fine
while installing the django I am getting this error "TypeError: LoadLibrary() argument 1 must be str, not None" and a very long exception, how can I solve this as it comes even when I am creating a virtual environment. I am learning Django and it was my first step so please answer accordingly. -
How to write a mixin in this case in order not to repeat the code
Django==2.2.5 There are three levels logically nested one inside another. The problem here is the repeating code in save method. Could you help me create a mixin not to repeat myself. class Level_1(PhraseMixin, ArchivedMixin, models.Model): def save(self, *args, **kwargs): """ If this level is archived, then make all sublevels archived too. """ if self.archived: level_2_set = self.level_2_set.all() for level_2_obj in level_2_set: level_2_obj.archived = True level_2_obj.save() super(Level_1, self).save(*args, **kwargs) class Level_2(ArchivedMixin, PhraseMixin, ValidateParentMixin, models.Model): parent_level = models.ForeignKey(Level_1, verbose_name="Level 1", on_delete=models.CASCADE) """ If this level is archived, then make all sublevels archived too. """ if self.archived: level_3_set = self.level_3_set.all() for level_3_obj in level_3_set: level_3_obj.archived = True level_3_obj.save() super(Level_2, self).save(*args, **kwargs) class Level_3(PhraseMixin, ArchivedMixin, WhereMixin, ValidateParentMixin, models.Model): parent_level = models.ForeignKey(Level_2, verbose_name="Level 2", on_delete=models.CASCADE) -
Django vs Flask. Which one should I use?
So I have recently decided to learn Django, and so far I am going pretty well. However, I have also heard Flask is good. Which one is better for a beginner like myself, who is only making small sites at the moment? Thank you for any help -
Redirection and edge case handling
I am trying to run some compute engine and google cloud dns functions when a form is submitted. I want to know how to do following things: 1) If every thing has been done properly then redirect to newly created sub domain. 2) If some error arises then redirect visitor to a default page stating your instance cannot be created.Please try again. I do not know how to redirect to a url which itself is being created during form save. class Company(models.Model): registrant = models.CharField("Name of the Registrant",max_length=120,null=True,blank=False) company = models.CharField("Name of the company",max_length=120, null=False) email = models.EmailField("Official Email Id of registrant",null=True,blank=False) designation = models.CharField("Designation at the company",max_length=120,null=True,blank=False) size = models.PositiveIntegerField("No. of employees",validators=[MinValueValidator(1)]) subdomain = models.CharField(max_length=120,null=True) registration_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.company class CompanySignupForm(forms.ModelForm): class Meta: model = Company fields = ('company','registrant','email','designation','size') def clean_email(self): email = self.cleaned_data.get("email") qs = User.objects.filter(email__iexact=email) if qs.exists(): raise forms.ValidationError("Cannot use this email. It's already registered") return email def clean_company(self): company = self.cleaned_data.get("company") qs = Company.objects.filter(company__iexact=company) if qs.exists(): raise forms.ValidationError("This company is already registered") return company def save(self,commit=True): company = super(CompanySignupForm,self).save(commit=False) email = self.clean_email() company.company = self.clean_company() company.registrant = self.cleaned_data.get('registrant') company.designation = self.cleaned_data.get('designation') company.size = self.cleaned_data.get('size') company.save() name = company.company.lower() + str(generate_random()) company.subdomain = name+".mysite.com" … -
How to get the instance of current plugin object in class-based view
I am developing a plugin for django-cms. Right now, I have a class BaseMyPlugin extending CMSPlugin class and I need to get an attribute base_attr from that class in class-based detail view (MyDetailView) context. What should I import (for modules) or override (for functions) for my view? The attribute I want to get is set in runtime so I have to get the instance. It is reachable in the template context because there is an global instance of plugin. But in the view context, I can not get such an instance. I have tried the following: Import BaseMyPlugin class in the view context. Failed because it was not the instance. Override render_to_response/get_context_data/get_object methods in MyDetailView class. Failed because the parameters of these methods didn't contain the base_attr attribute. Code for my view: class MyDetailView(DetailView): ``` I want to get the BaseMyPlugin.base_attr in this view ``` view_attr='to be set accouding to BaseMyPlugin.base_attr' Code for my CMSPlugin class: class BaseMyPlugin(CMSPlugin): # target attribute base_attr='some value set in runtime' I need to get the base_attr anyway to set view_attr in view in runtime. Could you help me plz? -
Fixing Migrations and Django migrating error
I wrote migration to my Django project and then ı applied ' make migrations and migrate' commands.For django there is no problem . But when ı run project django.db.utils.ProgrammingError: column providers_providerhotel.is_active does not exist LINE 1: ...hotel"."hash", "providers_providerhotel"."stars", "providers... ^ Exception ignored in: <function GEOSGeometry.__del__ at 0x1107fb830> Traceback (most recent call last): ImportError: sys.meta_path is None, Python is likely shutting down I think there is problem for adding column to database from my model.And for django , there is no problem it alerts ' ı wrote it to database there is no issue'. but it doesn't. Can anybody help to solve it ? model.py is_active = models.NullBooleanField() 003_providerhotel_is_active.py +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2019-09-12 07:48 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('providers', '0002_auto_20170203_0707'), + ] + + operations = [ + migrations.AddField( + model_name='providerhotel', + name='is_active', + field=models.NullBooleanField(), + ), + ] providers/init.py 'is_active': None, } -
I am confused in connecting postgresql with django
this is my first time to connect with any database i am using POSTGRESQL as database but i am stuck totally when i save signup information it not showing in the database table that i have created in pgadmin This is settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'accounts', 'USER':'postgres', 'PASSWORD':'****', 'HOST':'localhost' 'PORT':'5432' } } -
How to fix object representaions in django admin page on `LogEntry` model. django 2.2
I've added a code in my view to log every add action in my add_new_staff page. However, everytime I add a user on that page, the columns object_id and object_repr in LogEntry model in admin page gets this weird data representations(objects encircled with black pen): The objects encircled with red pen are the users I added on the django admin page, and it didn't get weird representations. These are the code I added in my add_staff_view : log = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(User).pk, object_id=User.id, # or any field you wish to represent here object_repr=repr(User.username), action_flag=ADDITION, # assuming it's a new object change_message=message,) # a new user has been added log.save() How can I fix this problem? Any help would be really appreciated. -
Django template re-rendering
So I have a django DetailView that I can easily render by getting all the data that I need from get_context_data in my class based view. But the problem is that each time to render this template I would need to choose a date in this template, get the date somehow and then re-render that same template from the date picked. I've been googling how to make this happen, there are something I could maybe do with AJAX, but maybe there is something easier to try, because I have little to no experience with AJAX/JS stuff class PlaceDetailView(LoginRequiredMixin, PermissionCheckMixin, PlaceViewMixin, DetailView): template_name = "places/place_detail.html" def get_context_data(self, **kwargs): context = super(PlaceDetailView, self).get_context_data(**kwargs) place = context.get("object") contract = Contract.objects.filter(pk=place.id).first() context["renter"] = User.objects.filter(pk=contract.renter_id).first() now = timezone.now() meters = MeterInstallation.objects.filter(places=place.id) context["active_meters"] = meters.filter(active_until__gte=now) context["old_meters"] = meters.filter(active_until__lt=now) context["services"] = ServiceTask.objects.filter(place=place) # Need to add more context values from more models, but the date has to be given, how? return context place_detail_view = PlaceDetailView.as_view() <div class="tab-pane fade show active" id="values" role="tabpanel" aria-labelledby="values-tab"> {% if values %} <div class="table-responsive-sm"> <table class="table small"> <thead> <tr> <th scope="col">#</th> <th scope="col">Values</th> </tr> </thead> <tbody> {% for value in values %} <tr> <th scope="row">{{ forloop.counter }}</th> <!-- todo add needed values … -
Use custom js file for FilteredSelectMultiple widget
I am struggling while trying to include FilteredSelectMultiple widget to user form. I finally managed to add it make make it show on regular user form (detailed way I did it in my previous question), but now I need to customize it a bit (resize, provide translations to buttons, tool-tips and similar things). I managed to find a similar question in this forum and determined that I need to edit SelectFilter2.js file (I do not know js, but managed to change required label/button text in it). Also will edited styles.css adjust widget size. And will put these files in my_app/static/ directory. But I cannot figure out - how to make django look at these custom files instead of original ones? Sorry if it noobish question, but please point me to the right direction, since I could not find any related material to it. My urls.py code: from django.urls import path from . import views from django.conf.urls import url from django import views as django_views urlpatterns = [ url(r'^jsi18n/$', django_views.i18n.JavaScriptCatalog.as_view(), name='jsi18n'), ] My forms.py code: from django.contrib.admin.widgets import FilteredSelectMultiple class DrgSkaiciuokle(forms.Form): bazine_kaina = forms.DecimalField(max_digits=5, decimal_places=2, required=True, label="Bazinė kaina", initial= BazineKaina.objects.get(), ) def clean_bazine_kaina(self): bazine_kaina = self.cleaned_data['bazine_kaina'] return bazine_kaina drg_pasirinkimas = forms.ModelMultipleChoiceField(queryset=DRGkodas.objects.all(), … -
Copying .csv file located on Heroku server to local drive
I have a Python/Django web application deployed to Heroku that writes information to a .csv file. Once the file has been written I want to pull it down from the Heroku server to the users local drive. I don't need to persist the file anywhere and so I am avoiding using S3 or storing in the database. I have used the Heroku "ps:copy" command which works but surely this would mean the user would need the Heroku CLI installed on their machine for this to work? Is there any other way? Thanks -
how to call class based view from another view, with parameters?
Say you used to call login_view(request, arg1, kwarg1='foo') Are you supposed to call LoginView.as_view()(request, arg1, kwarg1='foo') Additionally, In Drf, correct format is MyViewSet.as_view({ 'get': 'method_name' })(request, arg1, kwarg1='foo') And I wonder where the difference come from? -
How to use multiple forms in Django 2.1?
Sorry for asking similar questions, but other similar questions/answers do not help me with Django 2. Question: I have two actions, one is to show some data as a table. In the second form I edit this data and will save it as a table using django in the database. Here is some code: in simple_upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile" value="formOne"> <button class="btn btn-primary" type="submit">Upload</button> </form> The second form: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="mytable" value="formTwo"> <table class="table" border="1" id="tbl_posts"> <thead> <tr> ... </tbody> </table> <input type="submit" value="Submit"> </form> in views.py def simple_upload(request): if request.method == 'POST': ... if request.is_ajax(): return render(request, 'project/simple_upload.html', {'section': 'project', 'lines': zipped}) return render(request, 'project/list.html', {'section': 'project', 'lines': zipped}) return render(request, 'project/simple_upload.html') in urls.py: urlpatterns = [ ... path('', views.simple_upload, name='list'), ... ] in list.html: ... {% include "project/simple_upload.html" %} ... In this case only the first form works, the second one fails. Question 1: Can I do "if request.method == 'POST' and 'formOne' in request.POST:", I try but it does not react at all. Question2: How can I write two methods and assign them using urls.py? -
How to Implement Chained Dropdown List with Django with multiple fields?
I have created a form for a model(kit) which is connected by two different models by foreign key and manytomany field. Now, I want the form to automatically prefill data in the form fields as soon as an option is selected. This is my code. Code models.py # Parent model connected with both models class Kit(models.Model): kit_name = models.CharField(max_length=255, default=0) kit_info = models.CharField(max_length=255, default=0) components_per_kit = models.IntegerField(default=0) product_id = models.ManyToManyField(Product, related_name='kit_product') quantity_per_kit = models.IntegerField(default=0) kit_client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='kit_owner') # connected by foreign key class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_company = models.CharField(max_length=255, default=0) client_name = models.CharField(max_length=255, default=0) # connected by many to many field class Product(models.Model): product_id = models.IntegerField(default=0) product_name = models.CharField(max_length=255, default=0) product_short_code = models.CharField(max_length=255, default=0) product_description = models.CharField(max_length=255, default=0) template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2 class="mb-3">Add a new Kit</h2> <div class="row"> <div class="col-md-6 col-sm-8 col-12"> <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Save</button> <a href="{% url 'employee:products_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a> </form> </div> </div> {% endblock %} I followed this guide How to Implement Dependent/Chained Dropdown List with Django , and I want to expand this to have many fields being filled instead … -
Save rewrite method prevent data loss due to unsaved related object
I got the next models - Vacancy, Requirement, and Responsibility. Last two models related to Vacancy by foreign key. I want to rewrite save() method to create a page for every Vacancy, but there is an error on super(Vacancy, self).save(*args, **kwargs) line - save() prohibited to prevent data loss due to unsaved related object 'vacancy'. The default save works well, but begin to drop an error while I tried to rewrite it, why? class Vacancy(models.Model): title = models.CharField(max_length=100) short_description = models.CharField(max_length=300) slug = AutoSlugField(always_update=True,populate_from='title', unique=True) date_created = models.DateField(default=datetime.date.today()) background = models.ImageField(upload_to='uploads/images/') def __unicode__(self): return self.title class Meta: verbose_name_plural = 'Vacancy' def __str__(self): return self.title def save(self, *args, **kwargs): try: user = User.objects.filter(is_superuser=True)[0] vacancyPage = Title.objects.get(slug="vacancies",page__publisher_is_draft=True).page page = create_page(self.title, 'fullwidth.html', 'en', parent=vacancyPage, in_navigation=True, published=True) placeholder = page.placeholders.get(slot="content") add_plugin(placeholder, 'CMSVacancyPlugin', 'en', vacancy=self) super(Vacancy, self).save(*args, **kwargs) publish_page(page, user, 'en') except Exception as e: print(e) class Requirement(models.Model): text = models.CharField(max_length=250) vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE) class Responsibility(models.Model): text = models.CharField(max_length=250) vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE)