Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django (1.4...) 'Pincode' decryption not working
I am working on a old / outdated webapp and helping bring it into the world of 2018. The app is running on Django 1.4.19 and Python 2, both of which are slated to be upgraded to their newest LTS versions. However, before this upgrade can begin we have to fulfil some GDPR / licensing requirements. User can currently login to our app with both a password AND a 4 digit PIN-number. The PIN number is set on a UserProfile model, like so: class UserProfile(models.Model): DEFAULT_PINCODE = '0000' PIN_VALIDATOR = RegexValidator( regex='^\d{4}$', message=_('Error message.'), code='invalid_pin') MAX_LOGIN_ATTEMPTS = 4 LOGIN_BLOCK_DURATION = timedelta(hours=1) user = models.OneToOneField(User, related_name='profile') pincode = models.CharField( _('pin'), max_length=1000, null=True, blank=True, default=DEFAULT_PINCODE, validators=[PIN_VALIDATOR]) This is stored as a plain text and we want to hash/salt it as its saved in the database. To do this I created the following methods. def check_pin(self, raw_pincode): """ :param raw_password: :return: a boolean that indicates whether the raw_pincode matches self.pincode """ return check_password(raw_pincode, self.pincode) def save(self, *args, **kwargs): self.pincode = make_password(self.pincode) super(UserProfile, self).save(*args, **kwargs) The latter method ensures the pincode is encrypted. This method required me to change the pincode field from a IntegerField to CharField and returns a large encrypted string, but … -
Django base template location
I am creating a website using Django 2.0.7. I need to use a base template that is outside the purview of all applications, but can be inherited and used by templates in my other applications in the project. I have edited my settings.py file appropriately (as per the documentation), but still when I go the root (i.e. home) page of my site, I get a blank page - can anyone explain why? I have the following directory structure myproj ----manage.py ----app1 ----templates/ base.html index.html ----static/ ----myproj __initi__.py wsgi.py settings.py urls.py views.py # <- I added this The relevant parts of my settings.ini file looks like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['{0}/templates/'.format(BASE_DIR),], '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', ], }, }, ] views.py: from django.http import HttpResponse def index(request): return HttpResponse() Why can't django find my index.html ? -
Convert Decimal to MM:SS:MS Django
I am trying to convert a decimal value from my Django model into a time format of MM:SS:MS. For example: 97.13 as a decimal value would become 01:37:13. Is there any easy way to implement this with a raw SQL query in Django? Lets say I have this raw query: example = Example.objects.raw("""SELECT x.id, x.time FROM your_Table x WHERE x.id = %s""", [id]) Would it be better to execute the raw query and manipulate it in Python? How would I go about that? Could I loop the values e.g.? for examples in example: formatted_time = function(examples.time) Ultimately I'd like to pass my example object (with converted time) to my template. Thanks in advance. -
Django: Message appears twice
Anyone understands why my message always appears twice? print("Test") only appears once in the console which adds more to my confusion. In my base.html I implement the message framework through {% include "snippets/messages.html" %} @login_required def claim(request, organizer, event): context = {} user = request.user selected_event = get_object_or_404(Event, slug=event, organizer__slug=organizer) if request.method == 'POST': form = ClaimRewardForm( request.POST, initial={ 'event': selected_event, 'user': user, }, ) if form.is_valid(): new_reward_transaction = form.save(commit=False) new_reward_transaction.amount_paid = form.cleaned_data['reward'].price new_reward_transaction.ambassador = user.ambassador_profile new_reward_transaction.reward = form.cleaned_data['reward'] new_reward_transaction.save() # Add success message messages.add_message( request, messages.SUCCESS, _("Your reward claim was send for approval. You will receive a final confirmation via email.") ) print("TEST") return redirect( 'ambassadors:event', organizer=organizer, event=event, ) else: # TODO Marc: How to avoid repeating myself form = ClaimRewardForm( initial={ 'event': selected_event, 'user': request.user, }, ) # NEXT: Check if there is any reward that can be claimed return render(request, 'ambassadors/claim.html', { 'context': context, 'form': form, }) base.html <body> {% include "partials/header.html" %} {% include "snippets/messages.html" %} {% block content_before %} {% endblock %} <main role="main" class="container py-5"> {% block content %} {% endblock %} </main> -
django 2.0 debug toolbar not showing
I have followed the instructions on how to enable the Django Toolbar however, the toolbar does not appear. Does the toolbar still work with Django 2.0? -
Django-mptt display hierarchy as table
I am trying to display a hierarchical table as a normal table. model.py class Dimension_value(MPTTModel): name = models.CharField(max_length = 200, null=True, blank = True, default = '') parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name views.py def show_genres(request): return render(request, "accounts/dimension_detail.html", {'dimensions': Dimension_value.objects.all()}) dimension_detail.html <div class="container-fluid"> <div class="card"> <div class="card-body"> <h2>My dimensions</h2> {% load mptt_tags %} <ul> {% recursetree dimensions %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> </div> </div></div> Using django-mptt the lists show just fine. However I have no idea how to display this in a normal table. For example Europe|The Netherlands|Noord-Holland Europe|The Netherlands|Zuid-Holland Europe|Belgium |Vlaanderen -
Celery doesn't see tasks
Here is my celery config: config.celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery import sys from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config', backend=os.getenv('REDIS_URL', ), broker=os.getenv('CLOUDAMQP_URL') ) app.conf.update(BROKER_URL=os.getenv('CLOUDAMQP_URL', 'redis://localhost'), CELERY_RESULT_BACKEND=os.getenv('REDIS_URL', 'redis://localhost')) app.config_from_object('django.conf:settings', namespace='CELERY') sys.path.append(os.path.join(os.getcwd(), "applications")) app.autodiscover_tasks() TASK_SERIALIZER = 'json' Celery can't find tasks in following structure project_name/ apps/ users/ tasks.py config/ celery.py All my apps are registered in INSTALLED APPS and I'm using app registration via apps.py files. -
Django Rest Framework: How to add ManyToMany relationships?
I want to add a Many To Many relation ship using Django Rest Framework. What is the best way to achieve this? On a Django shell level what I want to do is to say ModelA.model_bs.add(model_b). How can this be done? I have achieved this using a generic.CreateAPIView and overwriting the perform_create() method like this: def perform_create(self, serializer): model_a = self.get_object() model_b = ModelB.objects.get(uuid=serializer.validated_data["model_b"]["uuid"]) model_a.modelbs.add(model_b) It's just this feels weird, since serializer.save() no longer gets called this way. Is this a good way? If not, how should I go about achieving this? I couldn't find anything about this in the documentation. Any help would be much appreciated! -
Uncaught ReferenceError: google is not defined (using Google Maps API)
I'm building a site using Django and when I wanted to put a map with markers(which coordinates I pull from database) it refuses to show the markers, throwing out the error: Uncaught ReferenceError: google is not defined On every single occurance of for(in the code below) <div id="map" style="height: 60%"></div> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 53.132330, lng: 23.159630}, zoom: 12 }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDIOOtr2iADzkBWq3r48fHiZRvnAFcWxHY&callback=initMap" async defer></script> {% for place in recent_attraction %} <script> var map = google.maps.Map(document.getElementById('map')); function setMarker() { var latlng = {lat: {{place.gps_x}}, lng: {{place.gps_y}}} var marker = new google.maps.Marker({ position: latlng, map: map }) } </script> {% endfor %} -
How to use Pagekite for webhooks?
I am trying to setup Intercom webhooks and have set up a local flask app. How do I capture data which is being POST to the pagekite address from Intercom webhooks? -
Custom Django FileField url widget won't upload any file in admin change_form
I have a Files table with information about uploaded files in a remote directory. This is the model for that table: class Files(models.Model): id = models.AutoField(primary_key=True) subjectid = models.ForeignKey('Subjects', models.DO_NOTHING, db_column='subjectid') filetypeid = models.ForeignKey(FileTypes, models.DO_NOTHING, db_column='filetypeid') filedescid = models.ForeignKey(FileDescription, models.DO_NOTHING, db_column='filedescid') filepath = models.CharField(max_length=45, blank=True, null=True) filename = models.FileField(upload_to='attachments/', blank=True, null=True) ispublic = models.IntegerField(choices=YESNO) extra_info = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.filename.name or '' class Meta: managed = False db_table = 'files' verbose_name_plural = 'files' I've created my own URL widget to replace the Django FileField url shown as 'Currently:' in the change_form template. The link points to a view that downloads the file. So far, so good it works but the problem is that when I try to add a new file I can select the new file with the Browse file button but when I click on Save the field filename field is empty and no file is uploaded. class MyAdminURLFieldWidget(URLInput): template_name = 'admin/widgets/url.html' def __init__(self, attrs=None): #final_attrs = {'class': 'vURLField'} final_attrs = {'type': 'file'} if attrs is not None: final_attrs.update(attrs) super(MyAdminURLFieldWidget, self).__init__(attrs=final_attrs) def get_context(self, name, value, attrs): context = super(MyAdminURLFieldWidget, self).get_context(name, value, attrs) context['current_label'] = _('Currently:') context['change_label'] = _('Change:') context['widget']['href'] = smart_urlquote('/DownloadView/' + str(value.instance.id) + '/attachment/') … -
I did everything rght..in python tutorial
I'm new to Python,...and started this localLibrary tutorial. It wont migrate on the MAc using 10.13.4. I believe there must be a version mismatch..I am almost there..please help? Running this in terminal instead of Idle. Loaded Django and all the files match the git resolve... python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/urls/resolvers.py", line 540, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/urls/resolvers.py", line 533, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.7/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 … -
Django use queryset method in annotation
I'm working on a Django project with models for courses and sections. I have made a custom aggregate method, 'stats' for sections which outputs a dictionary of values. I would like to group my sections by instructor and annotate the respective stats to each group. What I've tried so far: I first get a Course and store it as course. course.sections.values('instructor').annotate(section_count=Count('instructor')) I would like to do something like: course.sections.values('instructor').annotate(section_count=Count('instructor'), **stats) , although that clearly doesn't work This is my Section model: class Section(models.Model): course = models.ForeignKey(Course, related_name='sections') instructor = models.CharField() average_GPA = models.DecimalField() As = models.DecimalField() Bs = models.DecimalField() Cs = models.DecimalField() Ds = models.DecimalField() Fs = models.DecimalField() withdrawals = models.PositiveIntegerField() class_size = models.PositiveIntegerField() objects = SectionQueryset.as_manager() and this is the queryset code: class SectionQueryset(models.QuerySet): def stats(self): def safe_round(val): return round(val, 2) if (type(val) is float) else val data = self.aggregate( GPA=Avg('average_GPA'), A=Avg('As'), B=Avg('Bs'), C=Avg('Cs'), D=Avg('Ds'), F=Avg('Fs'), students=Sum('class_size'), withdrawals=Sum('withdrawals')) return {key: safe_round(value) for key, value in data.items()} -
Change the display value for a model field in Django
I have a simple model: class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) progress = models.DecimalField(max_digits=5, decimal_places=4) The progress field stores a percent value: For example 52% will be stored as 0.52 My form looks like this: class PersonForm(ModelForm): progress = forms.DecimalField(max_digits=4, decimal_places=2) class Meta: model = Person fields = ['first_name', 'last_name', 'progress'] def clean_progress(self): return self.cleaned_data.get('progress')/100 # convert 52% to -> 0.52 My question is, how can I convert this value back in my UpdateView? The form is prefilled with the values from the database. The value in the database is 0.52 but I want that the form is prefilled with 52. -
anaconda navigator will no longer start even through cmd, won't install or update or manage environments
I'm new to django and using the anaconda cloud environment. Its been working well for 3 months plus but as of 7-24-2018 is just wont launch the navigator or open through cmd. I cant manage environments or install packages. Using the anaconda prompt also gives me the same error upon launching. It started when I wanted to install django-Oscar but not having its dependencies I was forced to install the packages manually which in turn it needed cytoolz that needs Microsoft visual c++ build tools which I got to install aswel but the error persists. Please help me Copy/Paste of CMD Traceback: """ C:\Users\kaukau\Desktop>conda --version conda 4.5.4 C:\Users\kaukau\Desktop>anaconda-navigator Traceback (most recent call last): File "C:\Users\kaukau\Anaconda3\lib\site-packages\qtpy__init__.py", line 169, in from PySide import version as PYSIDE_VERSION # analysis:ignore ModuleNotFoundError: No module named 'PySide' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\kaukau\Anaconda3\Scripts\anaconda-navigator-script.py", line 6, in from anaconda_navigator.app.main import main File "C:\Users\kaukau\Anaconda3\lib\site-packages\anaconda_navigator\app\main.py", line 22, in from anaconda_navigator.utils.conda import is_conda_available File "C:\Users\kaukau\Anaconda3\lib\site-packages\anaconda_navigator\utils__init__.py", line 15, in from qtpy.QtGui import QIcon File "C:\Users\kaukau\Anaconda3\lib\site-packages\qtpy__init__.py", line 175, in raise PythonQtError('No Qt bindings could be found') qtpy.PythonQtError: No Qt bindings could be found C:\Users\kaukau\Desktop>conda install qt --force Traceback (most recent call last): … -
django rest framework saving M2M relation
I'm trying to create a cart with a m2m relationship, on saving this object the serializer raises two weird exceptions and if i changed the relation to one to many, everything works fine!. AttributeError: Got AttributeError when attempting to get a value for field quantity on serializer ItemSerializer. The serializer field might be named incorrectly and not match any attribute or key on the BranchItemList instance. Original exception text was: 'BranchItemList' object has no attribute 'quantity'. AttributeError at /api/carts/29 Got AttributeError when attempting to get a value for field item_list on serializer ItemSerializer. The serializer field might be named incorrectly and not match any attribute or key on the BranchItemList instance. Original exception text was: 'BranchItemList' object has no attribute 'item_list'. My input: { "items":[ {"item_list":350,"price":10,"quantity":20}, {"item_list":300,"price":10,"quantity":20} ] } Models: Serializers: -
Python2 transform exec from unqualified to qualified
I have to run a query with exec in my python code: strfin = '' a = [] a = qsearch.split(',') for li in range(0, len(a)): b = a[li].split(':') if b[0].upper() == 'ID': strfin = strfin + ',id__contains=' + "'"+b[1]+"'" elif b[0].upper() == 'TEST NAME': strfin = strfin + ',id_test__test_main__descr__contains=' + "'" + b[1].strip() + "'" elif b[0].upper() == 'TEST TYPE': strfin = strfin + ',thread_ttype__contains=' + "'" + b[1].strip() + "'" elif b[0].upper() == 'TEST GROUP': strfin = strfin + ',thread_tgroup__contains=' + "'" + b[1].strip() + "'" elif b[0].upper() == 'SCHEDULE': strfin = strfin + ',thread_stype__contains=' + "'" + b[1].strip() + "'" elif b[0].upper() == 'THREAD NAME': strfin = strfin + ',thread_main__contains=' + "'" + b[1].strip() + "'" elif b[0].upper() == 'START': strfin = strfin + ',thread_startd__contains=' + "'" + b[1].strip() + "'" elif b[0].upper() == 'STOP': strfin = strfin + ',thread_stopd__contains=' + "'" + b[1].strip() + "'" elif b[0].upper() == 'USER': strfin = strfin + ',id_test__user_id__contains=' + "'" + b[1].strip() + "'" afilexec = "%s%s%s" % ("activeThreads = t_threads.objects.filter(~Q(thread_status='DEAD'),", strfin[1:], ").select_related().distinct('thread_stag')") if i at the end of code write: exec(afilexec) System return error: SyntaxError: unqualified exec is not allowed in function 'tabrefresh' because it contains a nested function … -
Convert tax value
I have a database model which has a tax field. The tax is saved in the format: 0.19 which means 19% tax My goal is, that the user can enter the whole number for example 19 and this value will be converted to 0.19. If the user is showing the saved entry in a detail view this value should be also converted from 0.19 to 19% I have two ideas here but I don't know which solution is better. My first idea is to use the clean field from the form to convert the value and to display it I will modify the initial value. Or my second idea is to create a custom field and widget for this. -
how to access all models in one application to another application in same django project
the following is my installed appd in settings.py. I have imported all models of administrator to management in models.py-managemant using the code from administrator.models import * . Now I need to import models of management to administrator INSTALLED_APPS = [ 'administrator.apps.AdministratorConfig', 'vendoruser.apps.VendoruserConfig', 'management.apps.ManagementConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] when I used the code from management.models import * it shows the following errors Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f333c90ce18> Traceback (most recent call last): File "/home/jeslin/project/ProEnv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/jeslin/project/ProEnv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/jeslin/project/ProEnv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/jeslin/project/ProEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/jeslin/project/ProEnv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/jeslin/project/ProEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jeslin/project/ProEnv/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/jeslin/project/ProEnv/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/jeslin/project/ProEnv/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 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/jeslin/project/netfacer/administrator/models.py", line 8, in <module> from management.models … -
Add New Url in Django project
Hello Guys i got some problems about adding new url So here is my app url.py : url(r'^question/$', views.question_mark , name = 'question-mark'), here is my views.py : def question_mark(request): template = 'blog/question.html' return render(request,template) and here is myroject url.py : url(r'^blog/', include('blog.urls', namespace='blog')), but while i am typing www......com/en/blog/question i am getting page not found error what i am din wrong ? -
Accessing arguments passed to as_view
Is it possible to access arguments passed to as_view in the view class code? url(r'^api/business/$', RandomView.as_view(key='BUSINESS'), name='business'), In my view class, how would I access key='BUSINESS'? -
TemplateView not working in django get_absolute_url
I have one report app that manages all flagging of inappropriate content on my project. A member reporter can report another member reported for posting inappropriate content. Everything works fine and the report object is created, however it does not redirect to the thanks page in the end. but gets back to the same form page. What is highly strange is that when I paste http://127.0.0.1:8000/report/thanks/ in the address bar I surprisingly see the form page. usually the report page would have the url http://127.0.0.1:8000/report/Amanda/ What exactly is going wrong here. Below are my models.py class Report(models.Model): reporter = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='reporting_members') reported = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='reported_members') report_url = models.URLField(max_length=2000, blank=True, null=True) reported_at = models.DateTimeField(auto_now_add=True) reporting_choices = ( ('1', 'The images posted by this user are not relevant to the Post), ('2', 'Rude or abusive content, The words chosen by the user are inappropriate'), ('3', 'This user is asking me to change my review in return for favor '), ('4', 'Other'), ) reason_to_report = models.CharField(max_length=1, choices=reporting_choices) reason = models.TextField(blank=True, null=True) def __str__(self): return '{} is reporting {} for {}'.format(self.reporter, self.reported, self.reason_to_report) def get_absolute_url(self): return reverse('report:thanks') Below are my views.py class ReportCreateView(LoginRequiredMixin, CreateView): model = Report fields = ('reason_to_report', … -
type error __iint__ () missing required positional argument : on_delete [duplicate]
This question already has an answer here: Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries 5 answers i'm trying to run the command python manage.py migrate first_app but i'm getting the following error: File "C:\Users\a\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\a\Anaconda3\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\a\Anaconda3\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\a\Anaconda3\lib\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 955,_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 "C:\Users\a\Desktop\My_django\atom-master\first_project\first_app\models.py", line 18, in <module> class AccessRecord(models.Model):File "C:\Users\a\Desktop\My_django\atom-master\first_project\first_app\models.py", line 19, in AccessRecord name = models.ForeignKey(Webpage) TypeError: __init__() missing 1 required positional argument: 'on_delete' -
PROTECT deleting for ManyToMany field. DJANGO
I want to know the best practice of protecting deleting in ManyToMany field. I have two models: Department and Collaborator. I want to protect delete Department instance if it has at least one collaborator. models.py class Department(models.Model): """Model that represents department information.""" title = models.CharField(max_length=256) max_salary = models.IntegerField(default=0) class Collaborator(models.Model): """Model that represents collaborator information""" GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) surname = models.CharField(max_length=128, blank=True) gender = models.CharField(max_length=1, blank=True, choices=GENDER_CHOICES) salary = models.IntegerField(null=True, blank=True) departments = models.ManyToManyField(Department) class Meta: unique_together = ('first_name', 'last_name',) Note: Django 2.x, Python 3.7 -
Is using hidden fields in forms to send sensitive data a good option?
I am not much familiar with web security, but trying to develop a django based application. For payments, I am using Payu payment gateway, integrated successfully following the documentation. In payment url I have to post some sensitive information like - merchant_key, txnid along with user information, for sensitive data I am using hidden fields but I don't think it is a good option because anyone can see my sensitive data in source code. <form action="https://test.payu.in/_payment" name="payuForm" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="pOz2jZlcwLuLJRfBor9xqr4KIXtqGUCmcUSdZl6QeIXZnKc00ApNU2BxInA94Esy"> <input type="hidden" name="key" value="123456789"> <input type="hidden" name="hash" value="98231e7321875de86639070b07a1940effad7cac37e15e277f62e6d9c9488085cd060a3b9963864f2b10a334f2c04be4387b3fe24422d01cf5ed49d1a54c39f0"> <input type="hidden" name="txnid" value="833657e26b12fde34b620c67a3a8646c"> <input type="hidden" name="amount" value="1.0"> <input type="hidden" name="email" value="pankaj@gmail.com"> <input type="hidden" name="firstname" value="Pankaj"> <input type="hidden" name="phone" value="9950542612"> <input type="hidden" name="productinfo" value="Message showing product details."> <input type="hidden" name="surl" value="http://127.0.0.1:8000/orders/payment/success"> <input type="hidden" name="furl" value="http://127.0.0.1:8000/orders/payment/failure"> <!-- <input type="hidden" name="service_provider" value="" /> --> <div class="form-group"> <div class="col-md-12 col-sm-12"> Amount : 1.0 </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Purpose : Message showing product details. </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Name : Pankaj </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Email : pankaj@gmail.com </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Mobile : 9950542612 </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Transaction ID : 833657e26b12fde34b620c67a3a8646c </div> </div> <div class="form-group"> <div class="col-md-12 …