Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save a dictionary with key having value of type object
I am trying to save an object in mongodb using pymongo. I am calling an api which gives me and object and by iterating through object i am able to get fields and values. But problem is there may be some fields whose value is also an object and when i tried to store such fileds in mongodb i am getting errors. Error is can not encode object <....> models.py class UnusedResources(Document): field1 = fields.StringField(max_length=20) field2 = fields.DictField() python shell object = API #calling api d = dict() d = object.__dict__ #converted all fields of object into dict and stored in d d['field1'] = None d['field2'] = d client = MongoClient('127.0.0.1', 27017) db = client.CESdatabase collection = db.registration_unusedresources collection.insert_one(d) -
Error loading MySQLdb module: this is MySQLdb version (1, 3, 14, 'final', 0), but _mysql is version (1, 4, 1, 'final', 0)
_active.value = translation(language) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 177, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 159, in _fetch app = import_module(appname) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module import(name) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/init.py", line 6, in from django.contrib.admin.sites import AdminSite, site File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py", line 4, in from django.contrib.admin.forms import AdminAuthenticationForm File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/forms.py", line 6, in from django.contrib.auth.forms import AuthenticationForm File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/forms.py", line 17, in from django.contrib.auth.models import User File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 48, in class Permission(models.Model): File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 96, in new new_class.add_to_class('_meta', Options(meta, **kwargs)) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 264, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", line 124, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/usr/local/lib/python2.7/dist-packages/django/db/init.py", line 34, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 198, in getitem backend = load_backend(db['ENGINE']) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 113, in load_backend return import_module('%s.base' % backend_name) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module import(name) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 17, in raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: this is MySQLdb version (1, 3, 14, 'final', 0), but _mysql is version (1, 4, 1, 'final', 0) -
how to record the user activity log in django
How can I log the activities of a user in django-python? Is there any way to record the activities of a user in django? Suggest some methods possible -
How can i give pagination to Following View
I want pagincation of following UserListView class UserListView(LoginRequiredMixin, generic.TemplateView): template_name = 'users/users.html' paginate_by = 1 def get_context_data(self, **kwargs): context = super(UserListView, self).get_context_data(**kwargs) context['companies'] = Company.objects.exclude(company_is_deleted=True).exclude(company_name='Apollo') context['users'] = User.objects.filter(userprofile__user_role__id=2).exclude( Q(is_superuser=True) | Q(userprofile__user_is_deleted = True)| Q(userprofile__user_company__company_is_deleted=True) ) query = self.request.GET.get('query') if query: list_query = context['users'] context['users'] = list_query.filter(userprofile__user_company__company_name__icontains=query) return context -
how to get data according to category (which is not primary key)
trying to get data according to my cat(category) but in return getting data according to id (which i don't want) My urls.py: urlpatterns = [ path('cat/<int:post_cat>/', views.cat, name='cat'), ] (My Table Name is Post) def cat(request, post_cat): if request.method =="GET": cats = get_object_or_404(Post, pk=post_cat) # cats = get_object_or_404(Post, post_cat=cat) #also tried this not working return render(request, 'ads/cat.html',{'detail':cats}) else: pass -
Django can' t load Module 'debug_toolbar'
When I try running the project, Django can not load the django-debug-toolbar plugin. ModuleNotFoundError: No module named 'debug_toolbar' -
Scheduling tasks with dynamic arguments to run periodically with celery in django
I have a tasks that contains dynamic arguments I want to run periodically, how do I pass dynamic elements to the tasks arguments when the task is being called in django celery beat? Here is the task I want to run periodically: @task(bind=True) def generate_export(export_type, xform, export_id=None, options=None): """ Create appropriate export object given the export type. param: export_type param: xform params: export_id: ID of export object associated with the request param: options: additional parameters required for the lookup. binary_select_multiples: boolean flag end: end offset ext: export extension type dataview_pk: dataview pk group_delimiter: "/" or "." query: filter_query for custom queries remove_group_name: boolean flag split_select_multiples: boolean flag index_tag: ('[', ']') or ('_', '_') show_choice_labels: boolean flag language: language labels as in the XLSForm/XForm """ username = xform.user.username id_string = xform.id_string end = options.get("end") extension = options.get("extension", export_type) filter_query = options.get("query") remove_group_name = options.get("remove_group_name", False) start = options.get("start") export_type_func_map = { Export.XLS_EXPORT: 'to_xls_export', Export.CSV_EXPORT: 'to_flat_csv_export', Export.DHIS2CSV_EXPORT: 'to_dhis2csv_export', Export.CSV_ZIP_EXPORT: 'to_zipped_csv', Export.SAV_ZIP_EXPORT: 'to_zipped_sav', Export.GOOGLE_SHEETS_EXPORT: 'to_google_sheets', } if xform is None: xform = XForm.objects.get( user__username__iexact=username, id_string__iexact=id_string) dataview = None if options.get("dataview_pk"): dataview = DataView.objects.get(pk=options.get("dataview_pk")) records = dataview.query_data(dataview, all_data=True, filter_query=filter_query) total_records = dataview.query_data(dataview, count=True)[0].get('count') else: records = query_data(xform, query=filter_query, start=start, end=end) if filter_query: total_records = … -
Django url regex number
I am trying to add display number enter into url after time/ but when i am trying to add number more than 9 (two digit number) it is showing me Using the URLconf defined in MyFirstSite.urls, Django tried these URL patterns, in this order: admin/ ^time/([\d{1,2}])/$ The current path, time/12/, didn't match any of these. code: from django.contrib import admin from django.urls import path from . import Views from . import NewView from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), url(r'^time/([\d{1,2}])/$',Views.getTime) ] -
Pagination Not Working for multiple query
I am using pagination but is not woking. I have used with get_queryset() and it works. Why it is not working in get_context_view() class UserListView(LoginRequiredMixin, generic.TemplateView): template_name = 'users/users.html' paginate_by = 1 def get_context_data(self, **kwargs): context = super(UserListView, self).get_context_data(**kwargs) context['companies'] = Company.objects.exclude(company_is_deleted=True).exclude(company_name='Apollo') context['users'] = User.objects.filter(userprofile__user_role__id=2).exclude( Q(is_superuser=True) | Q(userprofile__user_is_deleted = True)| Q(userprofile__user_company__company_is_deleted=True) ) query = self.request.GET.get('query') if query: list_query = context['users'] context['users'] = list_query.filter(userprofile__user_company__company_name__icontains=query) return context -
Migration runs fine, but Django won't create a certain table
After I made some changes in my models, I dropped my database and started making migrations again. python3 manage.py makemigrations //it creates all the tables python3 manage.py migrate //the output is OK However, when I try to view my 4 tables, I see that one of them is missing. Here is my models.py file: from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractUser class UserTwo(AbstractUser): name = models.CharField(max_length=20, unique=True) surname = models.CharField(max_length=20, unique=True) username = models.CharField(max_length=20, unique=True) password = models.CharField(max_length=20, unique=True) email = models.EmailField(max_length=20, unique=True) use_in_migrations = True class Story(models.Model): title = models.CharField(max_length=200) story = models.TextField(default="") date = models.DateTimeField(default=datetime.now()) author = models.ForeignKey(UserTwo, on_delete=models.CASCADE) likes = models.IntegerField(default=0) comments = models.IntegerField(default=0) def __str__(self): return "%s %s %s " % (self.title, self.story, self.date) class Comment(models.Model): com = models.CharField(max_length=400) date = models.DateTimeField(default=datetime.now()) user = models.ForeignKey(UserTwo, on_delete=models.CASCADE) story = models.ForeignKey(Story, on_delete=models.CASCADE) def __str__(self): return "%s %s" % (self.com, self.date) class Like(models.Model): user = models.ForeignKey(UserTwo, on_delete=models.CASCADE, unique=False) story = models.ForeignKey(Story, on_delete=models.CASCADE, unique=False) timestamp = models.DateTimeField(default=datetime.now()) def __str__(self): return self.user.username The UserTwo model is the one that the migration is not creating a table of. Mind you that this is the model that the changes that I made before dropping the db happened in. … -
First migration to a new PostgreSQL database. ValueError: invalid literal for int() with base 10: ''
Have the models.py that have worked successfully with the SQLite database. Now trying to use PostgreSQL. If you look at the Traceback it seems like there is a string default value for an integer field. I just couldn't see it. Commented most of the fields, made migrations and still the same issue. Traceback Operations to perform: Apply all migrations: admin, auth, contenttypes, players, sessions, silk, users Running migrations: Applying players.0007_auto_20190130_1427...Traceback (most recent call last): File "D:\temp\YandexDisk\programming\py\nhl_web_app\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "c:\program files\python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "c:\program files\python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\program files\python37\lib\site-packages\django\core\management\base.py", lin e 316, in run_from_argv self.execute(*args, **cmd_options) File "c:\program files\python37\lib\site-packages\django\core\management\base.py", lin e 353, in execute output = self.handle(*args, **options) File "c:\program files\python37\lib\site-packages\django\core\management\base.py", lin e 83, in wrapped res = handle_func(*args, **kwargs) File "c:\program files\python37\lib\site-packages\django\core\management\commands\migr ate.py", line 203, in handle fake_initial=fake_initial, File "c:\program files\python37\lib\site-packages\django\db\migrations\executor.py", l ine 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=f ake_initial) File "c:\program files\python37\lib\site-packages\django\db\migrations\executor.py", l ine 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "c:\program files\python37\lib\site-packages\django\db\migrations\executor.py", l ine 244, in apply_migration state = migration.apply(state, schema_editor) File "c:\program files\python37\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "c:\program files\python37\lib\site-packages\django\db\migrations\operations\fiel ds.py", line 216, in … -
if request.method=="POST": is not working for edit function
I am able to load my instance with all my field populated but when I click submit, the edits doesn't save. Infact but adding print statements in my function, the code doesn't load beyond the if request.method=="POST":(refer to traceback). traceback [04/Feb/2019 15:38:30] "GET /testimonypost/ HTTP/1.1" 200 8081 Not Found: /testimonypost/.jpg [04/Feb/2019 15:38:30] "GET /testimonypost/.jpg HTTP/1.1" 404 17479 a [04/Feb/2019 15:38:35] "GET /40/testimony/edit HTTP/1.1" 200 5321 Not Found: /40/testimony/.jpg [04/Feb/2019 15:38:35] "GET /40/testimony/.jpg HTTP/1.1" 404 17476 [04/Feb/2019 15:38:56] "POST /40/testimony/ HTTP/1.1" 200 4224 Not Found: /40/testimony/.jpg [04/Feb/2019 15:38:56] "GET /40/testimony/.jpg HTTP/1.1" 404 17476 template <a href="{%url 'testimonyedit' objects.id %}">edit</a> urls.py urlpatterns = [ path('<int:id>/testimony/edit', views.TestimonyUpdae, name='testimonyedit'), ] views.py @login_required def TestimonyUpdate(request, id=None): instance=get_object_or_404(Testimony, id=id) if instance.user == request.user: form = TestimonyForm(instance=instance) print('a') if request.method == "POST": print('4') if form.is_valid(): form = TestimonyForm(request.POST or None, request.FILES or None) print('3') instance=form.save(commit=False) instance.save() context={ "instance":instance } return render(request, 'details.html', context) return render(request, 'variablized_form.html', {"form": form}) else: return HttpResponse('You are unauthorized to edit this post') -
Delete ManyToManyField in Django from admin page and on button click
I have two models as follows: models.py from django.db import models from django.contrib.auth.models import User class Skill(models.Model): skill = models.CharField(max_length=50) def __str__(self): return self.skill class Designer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=True) date_created = models.DateField(auto_now_add=True) profile_img = models.ImageField(upload_to="gallery",null=True, blank=True) skills = models.ManyToManyField(Skill, blank=True) experience = models.IntegerField(blank=True, null=True) account_type = models.CharField(max_length=10) def __str__(self): return self.user.username Designer model extends from User model and it has ManyToMany relationship with Skill model. I can add skills to designer instance from admin page but there is no delete option. How can I get the delete option on admin page? I also would like to add the delete functionality on button click. How can I add it in the code? -
Docker+Django (running through Docker template is not found but while running through manage.py it is running successfully )
I am trying to run my django app through docker container but while running through docker i am getting template does not found.I need to sync my django project with docker.Please help me out how to set . ----Django file structure---- django-sample> docker>python >Dockerfile newenv sampleproject templates docker-compose yml Docker file -- FROM python:2.7 COPY ./sampleproject /sampleproject WORKDIR /sampleproject RUN pip install -r Requirements.txt CMD ["python","manage.py","runserver","0.0.0.0:8000"] YML file-- version: '3' services: python: build: context: "" dockerfile: /docker/python/Dockerfile volumes: - ./sampleproject:/sampleproject ports: - "8000:8000" django.template.loaders.filesystem.Loader: /home/himanshu/django-sample/sampleproject/templates/h1.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.4/site-packages/django/contrib/admin/templates/h1.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.4/site-packages/django/contrib/auth/templates/h1.html (Source does not exist) -
Django - 'extra_fields' in CustomModelForm is giving 'Unable to lookuup' error in models inline interface when trying to load that form
I've one app named Question where i defined two models Question and Alternative in models.py as follows : class Question(models.Model): question = models.CharField(max_length=255, blank=False, null=False) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) rating = models.IntegerField(default=1) class Alternative(models.Model): alternative = models.CharField(max_length=255, blank=False, null=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) i've made a Custom form AlternativeForm where i've created a extra field which i want to appear in my Alternative forms as well as Question admin view where Alternative fields will appear in the inline view But the extra field value will not be saved in DB(cause i want to do some manual operations with the value of that fields). my AlternativeForm is as follows: class AlternativeForm(forms.ModelForm): extra_field = forms.BooleanField(required=False) def save(self, commit=True): extra_field = self.cleaned_data.get('extra_field', None) # will do something with extra_field here... return super(AlternativeForm, self).save(commit=commit) class Meta: model = Alternative fields = '__all__' and in my admin.py i've made an inline relationship between them as follows: class AlternativeInline(admin.TabularInline): form = AlternativeForm model = Alternative @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): inlines = [AlternativeInline,] @admin.register(Alternative) class AlternativeAdmin(admin.ModelAdmin): model = Alternative form = AlternativeForm I'm getting AttributeError: Unable to lookup 'extra_field' on Alternative or AlternativeInline in this case. I want to show those extra field in the Inline view of … -
why does Microsoft edge send empty http-referer on POST method?
Currently I'm working on Django1.11, i deployed my app using nginx with scheme 'https'. Everything is working fine and as expected on mozilla i.e. for normal POST call will render corresponding webpage, On reload & resubmit same POST will render 403 access denied. Problem only occurs when i'm testing same view in Microsoft EDGE browser. After calling normal POST method thrice, it directly throw me 403. Reason of 403 is 'REASON_NO_REFERER'. Microsoft Edge forwarding empty http-referer. I found patch for this: Add <meta name="referrer" content="origin-when-cross-origin" /> in <head> of html template and it's working fine. But still don't know what is wrong with Edge if i don't add this meta tag in header. Also, Does it cause any security vulnerabilities? Django explained why referer checking is must. Suppose user visits http://example.com/ # An active network attacker (man-in-the-middle, MITM) sends a # POST form that targets https://example.com/detonate-bomb/ and # submits it via JavaScript. # # The attacker will need to provide a CSRF cookie and token, but # that's no problem for a MITM and the session-independent # secret we're using. So the MITM can circumvent the CSRF # protection. This is true for any HTTP connection, but anyone # using … -
Export object with its related objects from a database in Django
What is the fastest way to export an object with all its relations from a database? I want to use it as a fixture for my tests. Now I call manage.py dumpdata <my_app>.<my_model> --pks <pks> for each model separately, but it takes a lot of time. Is there a smarter way of doing this task? Lets say we have this hierarchy of models: class Customer(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Car(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey('Customer', on_delete=models.PROTECT) class PartsToOrder(models.Model): type = modles.CharField(max_length=255) car = models.ForeignKey('Car') How could I export car object with id = 3528, including all parts to order and its owner into one fixture file. -
How to Insert foreign in other table using Django Rest Framework?
I'm using Django REST framework, I'm stuck in Inserting foreign-key data into another table. Please refer the scenario below: As given below code, I want to insert data in template table and also insert foreign-key relationship into template_owners table using the single post request. I tried few solutions but nothing worked as expected, Help is highly appreciated. Models.py: from django.db import models from datetime import datetime from django.utils import timezone # Template model starts here. class Template(models.Model): Yes = "Yes" No = 'No' STATUS = [ (Yes, "Yes"), (No, "No"), ] class Meta: db_table = "template" ordering = ("date",) uuid = models.CharField(max_length=64, null=False, primary_key=True) name = models.CharField(max_length=255, null=False) hypervisor = models.CharField(max_length=32, null=False) download_url = models.CharField(max_length=255, null=False) description = models.CharField(max_length=255, null=True) metadata = models.CharField(max_length=255, null=True) user = models.CharField(max_length=64, null=True) command = models.CharField(max_length=32, null=True) size = models.FloatField(null=False, blank=True, default=0) is_default = models.CharField(max_length=3, choices=STATUS, default=Yes) date_modified = models.DateTimeField(default=timezone.now) date = models.DateTimeField(default=timezone.now) owners = models.CharField(max_length=255, null=True) def __str__(self): return "Template [ uuid : {} ]" . format(self.uuid) # Template model ends here. # Template Owners model starts here. class TemplateOwners(models.Model): class Meta: db_table = "template_owners" ordering = ("date",) template_uuid = models.ForeignKey(Template, on_delete=models.CASCADE, db_column="template_uuid") gid = models.IntegerField(null=False, default=1) uid = models.IntegerField(null=False, default=1) date = models.DateTimeField(default=timezone.now) … -
Gunicorn log errors in Google Cloud Platform
I am running a Django REST API on Google Kubernetes Engine, using Gunicorn for my WSGI server. When my application encounters a 500 server error, the Python stack trace is not showing up in the GCP Logging console (in the "GKE Container" resource). In a different Django project of mine which uses Daphne for the ASGI/WSGI server, this traceback is being properly logged. Even more strange, the Gunicorn application has properly logged errors before, just a few weeks ago. Those errors appear in the Error Reporting console as well. To be clear, this is the type of information that I would like to see in the GCP logs: Internal Server Error: /v1/user/errant-endpoint Traceback (most recent call last): File "/path/to/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) ... File "/path/to/project/file.py", line 176, in my_file print(test) NameError: name 'test' is not defined For the Gunicorn project, some of the Python tracebacks are logged, like this one when Gunicorn is started: /usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1421: RuntimeWarning: DateTimeField User.last_login received a naive datetime (2019-02-04 05:49:47.530648) while time zone support is active. With 500 errors, however, only the HTTP info is logged: [04/Feb/2019:06:03:58 +0000] "POST /v1/errant-endpoint HTTP/1.1" 500 I've looked up the resources for setting up Stackdriver Logging … -
How to import models from outside Django BASE_DIR
I am working on a Django app in which I want to import some class/function from generator.py into my views.py to process an user-submitted input. My folder structure looks like this: project/ models/ __init__.py generator.py web/ django/ __init__.py settings.py urls.py wsgi.py django_app __init__.py views.py etc. Inside views.py, I have from ...models.generator import Generator When I try to run server, what I get is: ValueError: attempted relative import beyond top-level package I've seen many answers, but most are about manipulating sys.path or changing PYTHONPATH. I'm not sure how and where to do either cause I'm rather new to Django. Can someone tell me exactly which commands to run to allow the import to be done? -
how to clear cache from django database in version 2.1
i am facing weird issue, after wasting so much time i found out that this is the problem because of Database cache i made a Model Name "Profile" later flushdb / deleted it after few hours i made it again but getting this error "No such column" then i removed all sql3db files *.pyc file etc & run my model again (so django will recreate db structure {also performed migrate & makemigrations}) but still same error then i just renamed my db & the same code working now fine My problem is i have to use that old Old Model name again but not able to get because of db cache (or maybe something) please guide me. admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Profiles admin.site.register(Profiles) my model: from django.contrib.auth.models import User from django.db import models class Profiles(models.Model): # p2= models.CharField(max_length=14) phone = models.CharField(max_length=14) city = models.CharField(max_length=20) province = models.CharField(max_length=20) username2 = models.ForeignKey(User, on_delete=models.CASCADE) -
Validating fields on REST endpoint
I have an endpoint that when called should either update or create a user's profile. Inside this endpoint are 3 fields that need to be created or updated (avatar, bio, gender) Currently, I'm working with an UpdateAPIView like so: class UpdateOrCreateProfile(UpdateAPIView): serializer_class = ProfileSerializer def get_object(self): return Profile.objects.get(user=self.request.user) The serializer class looks like this: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' This works good, however, the validation is not working correctly. The form that is displayed has a clean_avatar function that does not accept images under 200x200 px. Like so: class ProfileForm(ModelForm): avatar = forms.ImageField(required=False, widget=forms.FileInput) bio = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, "placeholder": "Bio"}), max_length=200, required=False) class Meta: model = Profile fields = ['avatar', 'bio', 'gender'] def clean_avatar(self): picture = self.cleaned_data.get("avatar") if picture: w, h = get_image_dimensions(picture) if w < 200: raise forms.ValidationError("The image is %i pixel wide. It's supposed to be more than 200px" % w) if h < 200: raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h) return picture How can I make it so that the same validation that happens on the form, also happens in my endpoint? -
Django: what script function will reload the modelform after onchange?
What script function will trigger a reload of the modelform after a onchange event in a dropdown? Below, I am using 'product_type' as a drop down choice field. I have given it css_id='selector' The modelform contains a conditional script based upon this selector (from post Conditional fields in a ModelForm.Meta) The form changes given the choice and therefore I would need to update/reload to reflect the choice made in the drop-down. Which script function will do the trick in this case? in my html, <script> $("#selector").on("change", function() {..???.}); </script> Code: class ProductForm(ModelForm): class Meta: model = AllProduct fields = ('__all__') def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-4' self.helper.form_id = 'All-product' self.helper.form_method = 'post' self.helper.form_action = ('submit_form') self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) self.helper.layout = Layout( Field('product_type', css_class='form-control', css_id='selector'), Field('car_make', css_class='select2'), Field('boat_make', css_class='select2'), Field('number_wheels', step=1, min=0), Field('number_sails', step=1, min=0), ) product = 'product_type' if product == 'Car': fields_to_delete = ('boat_make', 'number_sails') else: fields_to_delete = ('car_make', 'number_wheels') for field in fields_to_delete: del self.fields[field] -
Django: Some of the attribute of a model shows None on template if it's empty
Some of the attribute of a model shows None on template if it's empty and I don't know why. For example, models.py class CustomUser(AbstractUser): nickname = models.CharField(max_length=20, null=True, blank=True) bio = models.TextField(max_length=500, null=True, blank=True) and html {{ user.nickname }} # shows None {{ user.bio }} # shows nothing What is the difference and how can I prevent it from showing None? -
With using login function with a database other than default - Django?
With using login function with a database other than default - Django? settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. DATABASES = { 'default':{}, 'mw': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '01_sistema', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '5432', } } thank you all for your attention.